简体   繁体   中英

Html.DropDownListFor binding problem

So I have these two tables - products, measurement_unit .

Products: (id int, name varchar(20) , id_um INT ) where id_um is a reference to the primary key of the measurement_unit table and id is the primary key of this table.

Measurement_unit: (id_um int, name varchar(20)). id_um is the primary key I mapped the two using LINQ to SQL.

When I want to create a new product I need to choose from a list of unit measurement, meaning a dropdownlist with their names but i want to bind the id for the selected one....

I'm doing this in the controller for the Create action (create a new product):

var items = new List<SelectListItem>();
            foreach (var t in db.measurement_unit)
                items.Add(new SelectListItem() { Text = t.name.ToString(), Value =t.id_um.ToString() });
ViewData["UM"] = new SelectList(items, "Value", "Text");

Now, for the view:

<%: Html.DropDownListFor(model=>model.id_um,  (IEnumerable <SelectListItem>)ViewData["UM"])%>

But I get the following error:

The ViewData item that has the key 'id_um' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.

I struggled with this thing before and I successfully made it work before but I accidentally deleted that project. Please tell me what am I doing wrong? Thanks!

I would recommend you using a view model instead of ViewData . It will make the code much cleaner/safer/refactor friendlier/Intellisense enabled/easier to unit test/magic strings free/....:

public class MyViewModel
{
    public int Id { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

Contoller:

public class HomeController: Controller
{
    public ActionResult Index() 
    {
        var model = new MyViewModel
        {
            Items = db.measurement_unit.Select(x => new SelectListItem
            {
                Value = x.id_um.ToString(),
                Text = x.name.ToString()
            })
        };
        return View(model);
    }
}

and finally in the strongly typed view:

<%= Html.DropDownListFor(
    x => x.Id,
    new SelectList(Model.Items, "Value", "Text")
) %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM