1

Relatively new to .Net MVC. Stumped by what appears to be a very simple problem.

I've got a few objects that are related to each other.

(as an example)

public class Asset{
  public int Id{get;set;}
  public AssetCategory AssetCategory {get;set;}
  public string Value {get;set;}
}

public class AssetCategory{
  public string Name{get;set;}
  public DateTime SomeDate{get;set;}
  public int Id{get;set;}
}

I want to create a new "Asset" object in my View and pre so I create an empty one with the AssetCategory set. Then pass it through as the model for that view.

I've tried having a @Html.HiddenFor(m=>m.AssetCategory) Which obviously fails as it doesn't how how to convert from that object to a string and back.

If I have @Html.HiddenFor(m=>m.AssetCategory.Id) then my ModelState is valid, But doesn't have all the information tied to the AssetCategory.

In this situation, do I just have to get the correct versions of any detached objects from my DB? As it stands, when I try to save my new Asset. I get an error because the non-nullable DateTime on the AssetCategory object is invalid.

4

3 回答 3

1

如果您只需要服务器上的类别信息,那么是的,在服务器上获取它并在保存之前附加到您的对象。

如果您的客户将更改它,您应该只在您的模型中包含 AssetCategory,即。你有一个用户可以选择的下拉菜单。在这种情况下,只需将 id 和有效项目列表添加到模型中。当您的模型被回发时,将其转换为您需要保存的对象。

换句话说,保留您必须保存到数据库的类,但创建一个单独的视图模型。

于 2013-04-30T19:57:33.667 回答
0

如果您只需要 Id,那么您的原始选项将起作用(但正如您所说,仅基于回发的数据不知道其他详细信息)。

@Html.HiddenFor(m=>m.AssetCategory.Id)

如果您想了解更多信息,请尝试使用 EditorTemplate 使其模块化。

@Html.EditorFor(m=>m.AssetCategory)

\Views\Assets\EditorTemplates\AssetCategory.cshtml

@model AssetCategory
@Html.HiddenFor(m=>m.Id)
@Html.DisplayFor(m=>m.Name)

话虽如此,您应该将 ViewModels 用于此类事情,而不是 EntityModels。我建议将其保留为仅传回 Id,然后在您的回发中,使用 AssetCategoryId 从数据库中加载完整的资产类别信息,然后再保存您的资产本身。

于 2013-04-30T20:51:31.540 回答
-1

出于性能考虑,默认情况下 EF 不会将所有数据加载到模型中。因此,您必须像这样手动加载它:

 public ActionResult MyAction(int id)
 {
    var asset = db.Assets.Single(a => a.Id == Id).Include(a => a.AssetCategory);

    return View(asset);
 }

Include方法会将相关对象加载到其模型中,因此您将获得所有属性并@Html.HiddenFor(m=>m.AssetCategory.Id)填充Id正确的数据。

查看加载相关对象以获取更多 EF 相关信息!

希望对您有所帮助!

于 2013-04-30T16:57:17.253 回答