asp.net mvc - Validating a drop-down in mvc4? -
asp.net mvc - Validating a drop-down in mvc4? -
i want create sure user selects value drop-down before submitting form. please have @ code below. doing wrong ? thanks
view
@model store.models.storedto list<store.models.countrydto> countrieslist= viewbag.countries; var countryitems = new selectlist(countrieslist, "cid", "cname"); @html.dropdownlistfor(x => x.countries.singleordefault().cid, @countryitems ) @html.validationmessagefor(x=>x.countries.singleordefault().cid) <input class="btn btn-info" type="submit" value="search" />
view-model
public class storedto { public ienumerable<countrydto> countries { get; set;} } public class countrydto { [displayname("cid")] [uihint("dropdownlist")] [required(errormessage = "please select country")] public string cid { get; set; } [required] public string cname { get; set; } }
the next lambda look not supported helpers:
x => x.countries.singleordefault().cid
only property access expressions supported.
the right way define cid property on view model hold selected country id dropdown:
public class myviewmodel { [displayname("cid")] [required(errormessage = "please select country")] public string cid { get; set; } ... }
and within view bind dropdown scalar property:
@html.dropdownlistfor( x => x.cid, new selectlist((ienumerable<store.models.countrydto>)viewbag.countries, "cid", "cname"), "-- select --" ) @html.validationmessagefor(x => x.cid)
asp.net-mvc razor asp.net-mvc-4
Comments
Post a Comment