【问题标题】:EditorTemplate for a productcategory (foreign key property)产品类别的 EditorTemplate(外键属性)
【发布时间】:2013-12-03 23:35:38
【问题描述】:

您好,我正在尝试为产品类别创建编辑器模板。

productcategorie 类是:

public class ProductCategorie
{
    public int Id { get; set; }
    public int Gewicht { get; set; }
    public string Naam { get; set; }
}

产品类是:

 public class Product
    {
        public int Id { get; set; }
        ...
        public ProductCategorie Categorie { get; set; }    
    }

现在在我自动创建的编辑视图中(脚手架)我得到了:

   <div class="form-group">
        @Html.LabelFor(model => model.Categorie, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Categorie)
            @Html.ValidationMessageFor(model => model.Categorie)
        </div>
    </div>

如您所见,我使用了 editorFor,因此我可以使用 EditorTemplate!

但是它崩溃了,因为它以某种方式没有给它一个模型。(它在模型上给出了 NullReferenceException,模型为空,但我需要它,以便我可以知道 SelectListItem 在 Selected 处必须具有 True !)

这是 EditorTemplates 中有问题的 ProductCategorie.cshtml 文件

@using Foo.Data
@using Foo.Models
@model ProductCategorie
@{
    var items = new List<SelectListItem>();
    using (var context = new FooDbContext())
    {
        List<ProductCategorie> categorielijst = context.ProductCategorieen.ToList();
        categorielijst.ForEach(x => items.Add(new SelectListItem { Text = x.Naam, Value = x.Id.ToString(), Selected = x.Id == ((ProductCategorie)Model).Id }));
    }
}
@Html.DropDownList("", items)

所以基本上我问的是如何在编辑具有实际上是外键项目的属性的项目时获取模型或当前选定项目的数据。

如果您有任何问题,请随时提出。

(我先用EF 6代码,ASP.Net MVC 5)

【问题讨论】:

  • 编辑器模板中没有@model 指令。你能确认这存在吗?
  • 是的,即使这样我仍然在模型上得到 NullException
  • 您能否更新您的问题中的代码以反映您已添加该指令.. 以便我们可以确定其正确存在?
  • 完成抱歉,我剪掉了一些代码来缩短它,但忘记了这个重要的部分:)
  • 所以,澄清一下:EditorTemplate 中的Model 在这一行为空:((ProductCategorie)Model).Id.. 对吗?顺便说一句:你真的不应该在你的视图中实例化一个新的DbContext .. :/

标签: c# asp.net asp.net-mvc entity-framework razor


【解决方案1】:

我们在 SO 聊天中解决了这个问题。

基本上,Model.Categorie 属性是 null.. 因此 EditorTemplate 将 null 传递给它。

很高兴为您提供帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    • 2021-01-09
    相关资源
    最近更新 更多