ASP.NET MVC – Custom CheckBox as Solution of “String was not recognized as a valid Boolean”

 

In case when you use Html.CheckBox(“IsNew”) the MVC render the html:

<input checked="checked" id="IsNew" name="IsNew" type="checkbox" value="true" />

<input name="IsNew" type="hidden" value="false" /> 

You can notice that there are two input element with identical name. Internet browsers does not send any value for checkbox if it is not checked. It is the reason why there is hidden input with value false. It work fine when you use POST form, but if you use GET form you see that a redirect url will be looked like this:

www.someurl.com?IsNew=true?IsNew=false 

and some links on a site can generate IsNew params like this:

www.someurl.com?IsNew=true,false

After use this link you can get the exception: String was not recognized as a valid Boolean,  because can not convert “true,false” to bool value. 

To solve the problem you can use the code:

<input type="checkbox"  id="IsNew-checkbox"  checked="checked" />     

<input type="hidden"  id="IsNew" name="IsNew" value="true"  />  

<script language="javascript" type="text/javascript" > 

  $('#IsNew-checkbox').click(function () {

      if ($('#IsNew-checkbox').is(':checked')) {

          $('#IsNew').val('true');

      } else {

          $('#IsNew').val('false');

       }

  });

 

</script>  

I used JQuery library to write the javascript snipet.

The above code you can transform to HTML helper and use it like this:

<%
   1: : Html.CustomCheckBox("IsNew",(bool)  ViewData["IsNew"]) 

%>

The code of the helper:

public static class Helpers

{

       public static MvcHtmlString CustomCheckBox(this HtmlHelper helper, string name,bool selected)

       { 

           string input;

           

           input= string.Format(@"

              <input type=""checkbox""  id=""{0}-checkbox""  {2} />     

                  <input type=""hidden""  id=""{0}"" name=""{0}"" value=""{1}""  />  

               <script language=""javascript"" type=""text/javascript"" >

                     $('#{0}-checkbox').click(function () {{

                         if ($('#{0}-checkbox').is(':checked')) {{

                             $('#{0}').val('true');

                         }} else {{

                             $('#{0}').val('false');

                          }}

                     }});

                 </script>  

               ",

                name,

                selected?"true":"false",

                selected ? "checked=\"checked\"" : "");            

 

           return MvcHtmlString.Create(input);                            

       }

 }

kick it on DotNetKicks.com

  • Share/Bookmark

Tags: ,

Leave a Reply