When i create a Html.CheckBox() in Asp.net MVC 2 i wonder there is a hidden field with that checkbox as well when i view its html, from where that hidden field is coming and what its purpose is?
1 Answer
From a comment in the ASP.NET MVC source code:
if (inputType == InputType.CheckBox) {
// Render an additional <input type="hidden".../> for checkboxes. This
// addresses scenarios where unchecked checkboxes are not sent in the request.
// Sending a hidden input makes it possible to know that the checkbox was present
// on the page when the request was submitted.
StringBuilder inputItemBuilder = new StringBuilder();
inputItemBuilder.Append(tagBuilder.ToString(TagRenderMode.SelfClosing));
TagBuilder hiddenInput = new TagBuilder("input");
hiddenInput.MergeAttribute("type", HtmlHelper.GetInputTypeString(InputType.Hidden));
hiddenInput.MergeAttribute("name", name);
hiddenInput.MergeAttribute("value", "false");
inputItemBuilder.Append(hiddenInput.ToString(TagRenderMode.SelfClosing));
return inputItemBuilder.ToString();
}
For example if the user doesn't check the value there's nothing sent to the server so if you are binding to some view model in your post action there won't be any value. The hidden field sends the value of false.
1 Comment
BritishDeveloper
In my opinion this is stupid. I've got a GET form and it's passing through conflicting paramaters. I.e. myField=true&myfield=false. Oh well back to pure HTML