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

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -