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" />
Return Value: It returns a string value which represent the value of the value attribute of a input checkbox field.
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.
Just add value="true" to the input tag. And use a hidden with value="false" as shown below.
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.
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.
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With