ASP.Net MVC - dropdown list for associated objects

2019-03-22 03:07发布

问题:

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.

回答1:

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"])%>