ASP.NET MVC sever-side validation of select (dropdown) list selected item -


when handling form posts in mvc, find myself writing some, somewhat, tedious code ensure posted drop down list selections valid items in list. idea is, there's nothing preventing post contains selected id not presented in drop down list. user insert own item drop down list (or otherwise post whatever want) or maybe form has been sitting in window long items available have changed. regardless of why happen, fact is, can't control data posted. here's example code of how deal with:

vm:

public class myviewmodel {     public string selecteditemid {get; set;}      public list<items> availableitems {get; set;} } 

view:

@using (html.beginform()) {     @html.dropdownlistfor(m => m.selecteditemid,                                 model.availableitems.select(i => new selectlistitem()                                 {                                     value = i.id.tostring(),                                     text = i.name,                                     selected = (model.selecteditemid == i.id)                                 }), "select one") } 

controller:

[httppost] public actionresult index(myviewmodel myvm) {     bool isvalid = true;      try     {         //reload available items         myvm.availableitems = repository.getavailableitems();          if(!modelstate.isvalid)         {             isvalid = false;         }         else         {             //make sure selecteditemid real item             if(!myvm.availableitems.any(i => i.id == myvm.selecteditemid))             {                 isvalid = false;                 myvm.selecteditemid = null;                 modelstate.addmodelerror("selecteditemid", "required"); //this gets interesting when selected id belongs nested vm in collection.             }         }          if(isvalid)         {             //finally can process form         }     }     catch(exception)     {         modelstate.addmodelerror("", "unable process submission. please try again.");     }      //return actionresult } 

setting error in modelstate gets ugly if selecteditemid belongs nested view model inside collection. seems should standard type of validation but, relative ease of performing other validation in asp.net mvc, pretty ugly , tedious. there easier way take care of this?

i think should @ tim coker's response here:

is possible update modelstate.isvalid manually?

basically, want make viewmodel class inherit ivalidatableobject, , put validate logic it. subsequent validation calls should fail if criteria isn't met (ie selecteditemid not in fresh db query)


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

Kivy: Swiping (Carousel & ScreenManager) -

jdbc - Not able to establish database connection in eclipse -