c# - Html.DropDownListFor binding problem -


so have these 2 tables - products, measurement_unit.

products: (id int, name varchar(20) , id_um int ) id_um reference primary key of measurement_unit table , id primary key of table.

measurement_unit: (id_um int, name varchar(20)). id_um primary key mapped 2 using linq sql.

when want create new product need choose list of unit measurement, meaning dropdownlist names want bind id selected one....

i'm doing in controller create action (create 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, view:

<%: html.dropdownlistfor(model=>model.id_um,  (ienumerable <selectlistitem>)viewdata["um"])%> 

but following error:

the viewdata item has key 'id_um' of type 'system.int32' must of type 'ienumerable<selectlistitem>'. 

i struggled thing before , made work before accidentally deleted project. please tell me doing wrong? thanks!

i recommend using view model instead of viewdata. make code cleaner/safer/refactor friendlier/intellisense enabled/easier 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 in typed view:

<%= html.dropdownlistfor(     x => x.id,     new selectlist(model.items, "value", "text") ) %> 

Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -