c# - How to get value from DropdownListFor? -


i cant figure out why posted viewmodel not having selected values in dropdownlistfor. instead showing ids in it.

in controller httpget edit action:

      model.maritalstatuses = new selectlist(maritalstatuses, "key", "value", 0);      ---      ---     static dictionary<int, string> maritalstatuses = new dictionary<int, string>()  {         {0, "--select one---"},         {1, "unmarried,"},         {2, "divorced, "},         {3, "widowed,  "},         {4, "separated,"},         {5, "annulled  "}     }; 

view :

 @html.dropdownlistfor(model => model.maritalstatus, model.maritalstatuses,"--select one--" , new { @class = "form-control" }) 

in controller httppost edit action:

     public actionresult edit(profileviewmodel model)             {     ---     // here keys in property instead of values in dropdownlistfor //for example : maritalstatus =2     ---     } 

in profileviewmodel:

public class profileviewmodel     { --- ---  public string maritalstatus { get; set; }         public selectlist maritalstatuses { get; set; } --- --- } 

any ?

in selectlist, key in dictionary posted when form submitted , not value in dictionary. if you'd value submitted instead use string value key. here's example builds selectlistitem instances in view (which prefer do):

static list<string> maritalstatuses = new list<string>() {     "unmarried",     "divorced",     "widowed",     "separated",     "annulled" };  public class profileviewmodel {   public string maritalstatus { get; set; }   public ilist<string> maritalstatuses { { return maritalstatuses; } } }  @html.dropdownlistfor(model => model.maritalstatus,                        model.maritalstatuses.select(s => new selectlistitem                            {                                text = s,                                value = s                            },                        "--select one--",                        new { @class = "form-control" }) 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

javascript - addthis share facebook and google+ url -

ios - Show keyboard with UITextField in the input accessory view -