ASP.Net MVC - 关联对象的下拉列表 [英] ASP.Net MVC - dropdown list for associated objects
问题描述
在我的应用程序中有两个模型: Product
和 ProductType
。 产品
引用 ProductType
(在DB中,它被命名为 ProductTypeId
),而 ProductType
有两列( Id
和名称
)。
我可以使用以下代码获得正确填充和显示在论坛上的下拉列表:
控制器:
var typeList = new SelectList(_entities.ProductType.ToList(),Id,Name);
ViewData [Types] = typeList;
查看:
code><%= Html.DropDownList(ProductType,(IEnumerable< SelectListItem>)ViewData [Types])%>
然而,我的问题就是它不会在Controller中更新模型。如果我离开代码,那么ModelState是无效的,因为视图中的 ProductType
字符串,但是,如果我把它改为其他任何东西,似乎我不能更长的时间是指控制器内的。
我刚刚尝试了相同的东西,它对我很好>
控制器:
public ActionResult Create()
{
configuredatorDataContext dc = new configuratorDataContext();
SelectList typelist = new SelectList(dc.Product_types.ToList(),id,Name);
ViewData [Product_Types] =类型列表;
ViewData.Model = new Product();
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Product createProduct)
{
// createProduct here包含正确的type_id wich
}
查看:
<%= Html.DropDownList(type_id,(IEnumerable< SelectListItem>)ViewData [Product_Types])%>
I have two models in my application: Product
and ProductType
. Product
has a reference to ProductType
(in the DB it's named ProductTypeId
), while ProductType
has two columns (Id
and Name
).
I can get the dropdown to be properly populated and displayed on the forum using the following code:
Controller:
var typeList = new SelectList(_entities.ProductType.ToList(), "Id", "Name");
ViewData["Types"] = typeList;
View:
<%= Html.DropDownList("ProductType", (IEnumerable<SelectListItem>) ViewData["Types"]) %>
However my problem becomes that it's not updating the model back in the Controller. If I leave the code as is, then the ModelState is invalid because of the ProductType
string in the view, However, if I change it to anything else, it seems I can no longer refer to it within the controller.
I just tried the very same thing and it worked for me just fine
controller:
public ActionResult Create()
{
configuratorDataContext dc = new configuratorDataContext();
SelectList typelist = new SelectList(dc.Product_types.ToList(), "id", "Name");
ViewData["Product_Types"] = typelist;
ViewData.Model = new Product();
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Product createProduct)
{
// createProduct here contains correct type_id wich
}
view:
<%= Html.DropDownList("type_id", (IEnumerable<SelectListItem>) ViewData["Product_Types"])%>
这篇关于ASP.Net MVC - 关联对象的下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!