asp.net mvc - Simple Validation for dropdownlist in mvc using (Html.ValidationMessage) -



asp.net mvc - Simple Validation for dropdownlist in mvc using (Html.ValidationMessage) -

controller

var productlist = enumerable.range(1, 80).select( x => new selectlistitem { value = x.tostring(), text = x.tostring() } ); viewdata["products"] = new selectlist(productlist.tolist(), "value", "text");

view

<%: html.dropdownlist("products", viewdata["products"] selectlist, "--select--")%> <%: html.validationmessage("products", "please select product list")%> //this doesnt works on (modelstate.isvalid) know dropdown list info coming //from view info not model , thats why model doesnt validate particular dropdown //list while validates other fields linked model, //just want know, how can validate above dropdownlist

you binding both name of ddl , values products. that's wrong. of course of study that's to the lowest degree problem code. far bigger , more serious problem using viewdata instead of using typed views , view models.

so there 2 possibilities:

the crappy one: have property on view model bind dropdown value.

[required(errormessage = "please select product list")] public string selectedproduct { get; set; }

and utilize property name first argument weakly typed dropdownlist helper , viewdata sec agrument:

<%= html.dropdownlist( "selectedproduct", viewdata["products"] selectlist, "--select--" ) %> <%= html.validationmessage("selectedproduct") %>

the right way: of course of study using real view models (i sick of repeating it, google, gazillions of answers, me, , on site on topic). this:

<%: html.dropdownlistfor( x => x.selectedproduct, model.products, "--select--" ) %> <%= html.validationmessagefor(x => x.selectedproduct) %>

asp.net-mvc asp.net-mvc-2 validation asp.net-mvc-3

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

c# - Can ProtoBuf-Net deserialize to a flat class? -

javascript - Change element in each JQuery tab to dynamically generated colors -