C# productcategory的EditorTemplate(外键属性)
您好,我正在尝试为productcategory创建editortemplate ProductCategory类是:C# productcategory的EditorTemplate(外键属性),c#,asp.net,asp.net-mvc,entity-framework,razor,C#,Asp.net,Asp.net Mvc,Entity Framework,Razor,您好,我正在尝试为productcategory创建editortemplate ProductCategory类是: public class ProductCategorie { public int Id { get; set; } public int Gewicht { get; set; } public string Naam { get; set; } } public class Product { public int Id
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; }
}
产品类别为:
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; }
}
现在在我自动创建的编辑视图(脚手架)中,我得到:
@LabelFor(model=>model.Categorie,新的{@class=“controllabel col-md-2”})
@EditorFor(model=>model.Categorie)
@Html.ValidationMessageFor(model=>model.Categorie)
如您所见,我使用editorFor,这样我就可以使用EditorTemplate了
但是它崩溃了,因为它不知何故没有给它一个模型。(它在模型上给出了一个NullReferenceException,该模型为null,但我需要它,这样我就可以知道SelectListItem在Selected上必须为True!)
以下是EditorTemplates中存在问题的ProductCategory.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)
@使用Foo.Data
@使用Foo.Models
@模型产品分类
@{
var items=新列表();
使用(var context=new FooDbContext())
{
List categorielijst=context.ProductCategorieen.ToList();
categorielijst.ForEach(x=>items.Add(新SelectListItem{Text=x.Naam,Value=x.Id.ToString(),Selected=x.Id==((ProductCategorie)Model).Id});
}
}
@Html.DropDownList(“,项)
因此,基本上我是在问,当编辑一个属性实际上是外键项的项时,如何获取当前选定项的模型或数据
如果你有任何问题,请随时提问
(我首先使用EF 6代码,ASP.Net MVC 5)我们在SO chat中解决了这个问题 基本上,
Model.categate
属性是null
。。因此EditorTemplate将null
传递给它
很高兴提供帮助:)编辑器模板中没有
@model
指令。你能确认这个存在吗?是的,即使如此,我仍然在模型上得到一个NullException。你能在你的问题中更新你的代码以反映你已经添加了那个指令吗。。这样我们就可以确保它在那里是正确的吗?很抱歉,我剪切了一些代码来缩短它,但是忘记了这个重要的部分:)所以,只是为了澄清:编辑器中的Model
在这一行是空的:((ProductCategorie)Model).Id
。。对的顺便说一句:你真的不应该在你的视图中实例化一个新的DbContext
:/