asp.net mvc - How to use SelectList in View without a model? -


i have read many times experts of mvc saying if use selectlist, it's best have ienumerable<selectlist> defined in model.
example, in question.
consider simple example:

public class car() {     public string mybrand { get; set; }     public ienumerable<selectlistitem> carbrands { get; set; } // sorry, mistyped, shoudl selectlistitem rather carbrand } 

in controller, people do:

public actionresult index()  {     var c = new car     {         carbrands = new list<carbrand>         {             // , here goes options..         }     }     return view(c); } 

however, pro asp.net mvc, learned way of creating new instance.

public actionresult create() // {     return view() } [httppost] public actionresult create(car c) {     if(modelstate.isvalid) // add database } 

my question is: how should pass selectlist view? since in method there no model existing, there seems no way this.
using viewbag, told avoid using viewbag causes problems. i'm wondering options.

you create viewmodel has properties of car want on form make selectlist property of viewmodel class

public class addcarviewmodel {    public int carname { get; set; }    public string carmodel { get; set; }    ... etc     public selectlist mylist    {       get;       set;    } } 

your controller like

public actionresult create() // {     addcarviewmodel model = new addcarviewmodel();     return view(model) }  [httppost] public actionresult create(addcarviewmodel c) {     if(modelstate.isvalid) // add database } 

markup

@html.dropdownlistfor(@model => model.listproperty, model.mylist, ....) 

Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -