c# - How can I pass list of strongly type objects from controller to a dropdown on a view? -




i pass list of typed object dropdown located on view.

usually achieve used viewbags in following example:

public actionresult chooselevel() {       list<levels> levellist = getalllevels();       viewbag.levellist = levellist        var model = new levels();      return view(model); } 

and write on view, , levels listed there:

<div class="form-group">     @html.labelfor(model => model.levelid, new { @class = "control-label col-md-3 col-sm-3" })     <div class="col-md-9 col-sm-9">         @html.dropdownlistfor(model => model.levelid, new selectlist(viewbag.levellist, "levelid", "levelname"), "", new { @class = "form-control" })     </div> </div> 

but i'm wondering can pass list of levels there, , choose them dropdown list, without storing them viewbag first? example :

public actionresult chooselevel() {      list<levels> levellist = getalllevels();      return view(levellist); } 

on view accept multiple items writing ienumerable on view:

@model ienumerable<levels> 

and after somehow choose 1 item , post server?

how can solve issue?

you need add list existing model or view model:

class modelname { public virtual ienumerable<selectlistitem> lsttypes { get; set; } public virtual int inttypeid { get; set; } //other existing properties here } 

on controller, can add list model before return view:

            modelname objmodel = new modelname();             list<levels> levellist = getalllevels();              objmodel.lsttypes = levellist.select(y => new selectlistitem()             {                 value = y.levelid.tostring(),                 text = y.levelname.tostring()             });          return view(objmodel); 

then can display on view:

@model modelname //first parameter id selected user when post //second parameter enumerable list of dropdown //third parameter default option optional, , last html attributes @html.dropdownlistfor(c => c.inttypeid, model.lsttypes , "please select item", new { @class = "form-control" }) 




wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -