asp.net mvc - How do I validate only certain strings in C# MVC? -
how validate string in c#? example if have 4 colors red, blue, green , black wants user enter these colors. if user enters other color such white than, code throws error " how use in model validation in mvc c#?
for example: model:
public int id {get; set;} public string color {get; set;}
controller:
[httppost] public actionresult create( [bind(include = "id, color")] tblcolor mycolor) { try { if (modelstate.isvalid && modelstate != modelstate) if(mycolor == red, green, blue, black) { db.projects.add(mycolor); db.savechanges(); return redirecttoaction("index"); } else { // error == "you allow insert 1 of red, blue, green, black"; } } } catch (exception) { // error message } return view(mycolor); }
i recommend using dropdown box values, still doesn't validate response.
for server side validation, , assuming have value coming in via parameter, work:
[httppost] public actionresult submit(string color) { string[] validcolors = new string[] { "red", "blue", "green", "black" }; if (!validcolors.contains(color)) { viewbag.errormessage = color + " not valid color."; return view(); } }
Comments
Post a Comment