asp.net mvc - Validate static dropdown in MVC5 -
i have on drop down.
model
[required(errormessage = "please selectvehicle")] public string vehiclerequested { get; set; } index.cshtml
@html.dropdownlist("vehiclerequested", new list<selectlistitem> { new selectlistitem{ text="active", value = "1" }, new selectlistitem{ text="not-active", value = "0" } }) @html.validationmessagefor(model => model.vehiclerequested) i cannot see required feild validation append, m wrong , please suggst
your dropdownlist has 2 items, 1 value="0", other value="1" both "0" , "1" valid strings (neither null) validation passes. property can never invalid never validation error.
its not clear why binding int value string property, , fact display 2 values ("active" , "not-active") suggests property should bool.
if want add option such "-please select-" results in validation error if 1 of other 2 options not selected, use overload accepts optionlabel
@html.dropdownlist("vehiclerequested", new list<selectlistitem> { new selectlistitem{ text="active", value = "1" }, new selectlistitem{ text="not-active", value = "0" } }, "-please select-") @html.validationmessagefor(model => model.vehiclerequested) this add first option <option value>-please select-</option>. note value attribute not have value, if selected when submit, vehiclerequested null , see error message.
side note: suggest use typed helper - @html.dropdownlistfor(m => m.vehiclerequested, ...) , build selectist in controller , pass view viewbag or (better) view model property.
Comments
Post a Comment