asp.net mvc - Dropdownlistfor returns null value -
i have customer class property gender. created list of gender type contains , id number , gender type. when form submitted, getting null value.
view
@model movierentals.viewmodel.customerview <div class="form-group"> <h4>@html.labelfor(l => l.customer.birthdate)</h4> @html.dropdownlistfor(l => l.customergender, new selectlist(model.customergender, "genderid", "gendertype"), "select gender", new { @class = "form-control" }) </div>
model
public class customerview { public ienumerable<membershiptype> membershiptypes{ get; set; } public customer customer { get; set; } public list<genderclass> customergender{ get; set; } } public class genderclass { public int genderid { get; set; } public string gendertype { get; set; } }
controller
public actionresult new() { var membershipty = _context.memebershiptype.tolist(); var viewmodel = new customerview(); viewmodel.customergender = new list<genderclass>() { new genderclass(){ genderid = 1, gendertype = "male"}, new genderclass() { genderid = 2, gendertype = "female"} }; viewmodel.membershiptypes = membershipty; return view(viewmodel); }
you need 2 properties: 1 hold selected value , 1 hold options. 1 holds options should ienumerable<selectlistitem>
. genderclass
class superfluous.
also, using integer id value doesn't make sense when meaning of value not obvious. here, fact 1
means male
exists in new
action. anywhere else, have repeat logic (which introduces opportunities errors, e.g. male 1
or 0
). further, if decide change values, must remember change them everywhere. if want use integer id, should abstract away meaning somewhere, enum, static class, database table, etc. far better choice keep string, , use dropdown merely enforce normalization of string value.
public string customergender { get; set; } public ienumerable<selectlistitem> customergenderchoices { { return new list<selectlistitem> { new selectlistitem { value = "male", text = "male" }, new selectlistitem { value = "female", text = "female" } } } }
then, in view:
@html.dropdownlistfor(m => m.customergender, model.customergenderchoices, "select gender", new { @class = "form-control" })
alternatively, if use enum:
public enum genders { male = 1, female = 2 }
then, in view model, need 1 property, store value:
public genders customergender { get; set; }
then, in view, can make use of enumdropdownlistfor
:
@html.enumdropdownlistfor(m => m.customergender, "select gender", new { @class = "form-control" })
as enum, value stored int, benefit here have strongly-typed association between integer values , mean. example, rather doing like:
if (customer.customergender == 1) // male
you can do:
if (customer.customergender == genders.male)
obviously, second version more obvious in meaning.
Comments
Post a Comment