c# - How do I validate a checkbox value in ASP.NET MVC? -


i have following viewmodel

public class reportfilters {     [required]     public datetime { get; set; }      [required]     public datetime { get; set; }      [required]     public int userid { get; set; }      public bool iscorrect { get; set; } }  

i pass either value 1 or 0 when call route iscorrect modelstate.isvalid returning false.

this started happen after added public bool iscorrect { get; set; }

here how controller action

[httppost] [validateantiforgerytoken] public jsonresult gettotals([bind(include = "from,to,userid,iscorrect ")] reportfilters reportfilters) {     if (modelstate.isvalid)     {         somemodel results;          if(reportfilters.iscorrect)         {             results = conn.database.sqlquery<somemodel>(somequery, from, to).tolist();         } else          {             results = conn.database.sqlquery<somemodel>(someotherquery, from, to).tolist();         }          return json(results, jsonrequestbehavior.allowget);     }      return json(new { }, jsonrequestbehavior.allowget);  } 

question

how can correctly validate value of check box? if value 1 should true otherwise false.

ensure passing parameters properly

have tried passing true or false explicitly (i.e. controller/action?iscorrect=true) opposed 0 or 1?

a checkbox should bind directly boolean value. you'll need ensure name attribute of checkbox matches parameter or model property (i.e. iscorrect) :

<!-- using plain checkbox --> <input name='iscorrect' type='checkbox' /> <!-- using html helper --> @html.checkbox("iscorrect") 

you can see working example demonstrating this below :

enter image description here


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -