ASP.Net MVC - a drop-down list for related objects

There are two models in my application: Productand ProductType. Producthas a link to ProductType(it is called in the database ProductTypeId), and ProductTypehas two columns ( Idand Name).

I can get a drop-down list that will be correctly 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 is that it does not update the model in the controller. If you leave the code as it is, then ModelState is invalid due to a line ProductTypein the view. However, if I change it to something else, it looks like I can no longer reference it in the controller.

+3
source share
1

, .

:

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

Source: https://habr.com/ru/post/1704459/


All Articles