c# - Adding drop down list to mvc page -


this giving me hard time implement. i've generated controller , view handle updating model.

however in create.cshtml need add drop down database users (using db.users.tolist()) populate dropdown.

<div class="form-group">     @html.labelfor(model => model.userid, htmlattributes: new { @class = "control-label col-md-2" })     <div class="col-md-10">         // @html.editorfor(model => model.userid, new { htmlattributes = new { @class = "form-control" } })         @html.dropdownlistfor(model => model.userid, viewdata["u"] ienumerable<selectlistitem>)     </div> </div> 

so i've taken @html.editorfor() , replaced @html.dropdownlistfor() show dropdown list. , work error when click submit.

the viewdata item has key 'userid' of type 'system.string' must of type 'ienumerable'.

here's model.

public class pdf {     [key]     public int id { get; set; }     public string userid { get; set; }     public guid fileguid { get; set; }     public string filename { get; set; }     public string filelocation { get; set; } } 

and create controller.

public actionresult create() {     if (modelstate.isvalid)     {         var u = db.users.select(x => new { userid = x.id, username = x.username }).tolist();         //u[0].username         viewbag.userinfo = new system.web.mvc.multiselectlist(u, "userid", "username");         ienumerable<selectlistitem> u1 = new selectlist(db.users.tolist(), "id", "username");         viewdata["u"] = u1;     }     return view(); }  [httppost] [validateantiforgerytoken] public actionresult create([bind(include = "id,userid,fileguid,filename,filelocation")] pdf pdf) {     if (modelstate.isvalid)     {         db.tblpdf.add(pdf);         db.savechanges();         return redirecttoaction("index");     }     return view(pdf); } 

i feel i'm there. need push in right direction make work.

this how can make selectlistitems

viewdata["items"] = db.userprofiles     .select(x => new selectlistitem() { text = x.username, value = x.userid.tostring() }); 

this how use it

@html.dropdownlistfor(model => model.userid, viewdata["items"] ienumerable<selectlistitem>) 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -