ASP.Net MVC - 为关联对象下拉列表 [英] ASP.Net MVC - dropdown list for associated objects

查看:125
本文介绍了ASP.Net MVC - 为关联对象下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序两种型号:产品 ProductType 产品有一个参考 ProductType (以它命名为DB ProductTypeId ),而 ProductType 有两列(编号名称)。

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).

我可以得到下拉菜单进行适当填充,然后使用以下code显示在论坛上:

I can get the dropdown to be properly populated and displayed on the forum using the following code:

var typeList = new SelectList(_entities.ProductType.ToList(), "Id", "Name");
ViewData["Types"] = typeList;

查看:

<%= Html.DropDownList("ProductType", (IEnumerable<SelectListItem>) ViewData["Types"]) %>

不过我的问题就它没有更新模型回到控制器。如果我离开了code原样,那么的ModelState是无效的,因为在视图中的 ProductType 字符串,但是,如果我将其更改为别的,似乎我不能再引用它的控制器中。

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

控制器:

 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 
    }

查看:

  <%= Html.DropDownList("type_id", (IEnumerable<SelectListItem>) ViewData["Product_Types"])%>

这篇关于ASP.Net MVC - 为关联对象下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆