.NET MVC剃刀的下拉列表中的外键 [英] .net mvc razor dropdowns for foreign keys
问题描述
好吧,这似乎简单,但让我目瞪口呆。
Ok, this seemed simple, but is making my head spin.
我创建的模型的基础上codeFirst。
I have created models based on CodeFirst.
public class Category
{
public int ID { get; set; }
[StringLength(255, MinimumLength = 1)]
public string Name { get; set; }
}
public class SubCategory
{
public int ID { get; set; }
public Category category { get; set; }
[StringLength(255, MinimumLength = 1)]
public string Name { get; set; }
}
现在,当我自动生成控制器和视图的子类别它(开箱即用),让我创造新的子类别的对象,而无需指定类别(甚至通过它正确地创建一个外键关系的分类表数据库)。
Now when i auto-generate the controller and view for SubCategory it (out-of-the-box) lets me create new SubCategory objects without specifying the Category (even through it correctly creates a foreign key relation to the Category table in the DB).
因此,虽然确定我,我只是下降一个下拉的create.cshtml文件,并将其使用。
So i though ok, i'll just drop a drop down in the create.cshtml file and have it use that.
经过一些,而我成功加入该到控制器:
after some while i succeed by adding this to the controller:
public ActionResult Create()
{
ViewBag.Categories = new SelectList(db.Category.ToList(),"ID","Name");
return View();
}
和这对观点:
@Html.DropDownList(model => model.category, "Categories")
但现在的对象不会自动赶上,我想用这对我的外键,所以,当我停止code在POST方法仍显示为NULL的类别字段的对象。
But now the object does not automatically catch that i want to use this for my foreign key, so when i stop the code at the POST method it still displays the object with NULL in the category field.
我想我的问题是双重的。我应该怎么做?如果我的方法是正确的,到目前为止,我在想什么?
I guess my question is twofold. How should i do this? and if my method is right so far, what am i missing?
我只是想这是保存在子类别表中的新对象包括外键类别。
I just want the new object which is saved to the SubCategory table to include the foreign key to Category.
希望这是有道理的。
推荐答案
最简单的方法是在你的定义
类的CategoryId
的标量属性子类别
Easiest way is to define a scalar property named CategoryId
in your SubCategory
class
public class SubCategory
{
public int ID { get; set; }
public int CategoryID { get; set; }
public Category category { get; set; }
[StringLength(255, MinimumLength = 1)]
public string Name { get; set; }
}
然后正确映射它EF
Then correctly map it in EF
在你把
@Html.DropDownListFor(
model => model.CategoryID, category SelectList instance)
)
另一种方法是创建一个自定义模型绑定绑定类别
键入
这篇关于.NET MVC剃刀的下拉列表中的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!