views:

3172

answers:

2

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.

+2  A: 

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"])%>
Alexander Taran
A: 

It works also for me. Thank you!

raffaeu
This should probably be a comment of some answer... It's completely wrong to write this kind of comments/observations as an answer on Stackoverflow. If you don't have enough reputation to write comments, then don't write answers that are not answers either. Be patient and you'll get to sufficient points.
Robert Koritnik