Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc: why is Html.CheckBox generating an additional hidden input

Tags:

asp.net-mvc

I just noticed that Html.CheckBox("foo") generates 2 inputs instead of one, anybody knows why is this so ?

<input id="foo" name="foo" type="checkbox" value="true" /> <input name="foo" type="hidden" value="false" />  
like image 290
Omu Avatar asked Apr 23 '10 08:04

Omu


People also ask

What does a checkbox input return?

Return Value: It returns a string value which represent the value of the value attribute of a input checkbox field.

What is hidden field in ASP NET MVC?

Here we will learn how to create or use hidden fields in asp.net mvc with a simple example using HTML helpers. Before going in-depth, let's understand the definition of hidden fields. The hidden fields are controls that allow us to store data or information on a page without displaying it.

How can get checkbox value in ASP NET MVC?

Just add value="true" to the input tag. And use a hidden with value="false" as shown below.

What is HTML HiddenFor in MVC?

Html. HiddenFor<TModel, TProperty> extension method is a strongly typed extension method generates a hidden input element for the model property specified using a lambda expression. Visit docs.microsoft.com to know all the overloads of HiddenFor() method. Example: HiddenFor() in Razor View.


2 Answers

If checkbox is not selected, form field is not submitted. That is why there is always false value in hidden field. If you leave checkbox unchecked, form will still have value from hidden field. That is how ASP.NET MVC handles checkbox values.

If you want to confirm that, place a checkbox on form not with Html.Hidden, but with <input type="checkbox" name="MyTestCheckboxValue"></input>. Leave checkbox unchecked, submit form and look at posted request values on server side. You'll see that there is no checkbox value. If you had hidden field, it would contain MyTestCheckboxValue entry with false value.

like image 155
LukLed Avatar answered Sep 16 '22 15:09

LukLed


You can write a helper to prevent adding the hidden input:

using System.Web.Mvc; using System.Web.Mvc.Html;  public static class HelperUI {     public static MvcHtmlString CheckBoxSimple(this HtmlHelper htmlHelper, string name, object htmlAttributes)     {         string checkBoxWithHidden = htmlHelper.CheckBox(name, htmlAttributes).ToHtmlString().Trim();         string pureCheckBox = checkBoxWithHidden.Substring(0, checkBoxWithHidden.IndexOf("<input", 1));         return new MvcHtmlString(pureCheckBox);     } } 

use it:

@Html.CheckBoxSimple("foo", new {value = bar.Id}) 
like image 29
2 revs Avatar answered Sep 20 '22 15:09

2 revs