1

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.