1

When you start an ASP.NET MVC project in Visual Studio 2008, you get a fully loaded site template, including login forms and the like. In the default form to login, you will find this in the markup...

<%= Html.CheckBox("rememberMe") %>

When you view the source in the browser, you will see that this renders to...

<input id="rememberMe" name="rememberMe" type="checkbox" value="true" />
<input name="rememberMe" type="hidden" value="false" />

What is the purpose of this hidden field, and the default values? Is there a reason for this? Makes no sense to me.

1 Answer 1

2

This is the comment from the ASP.NET MVC source:

// 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.

In short: unchecked checkboxes (values) are not sent in the request. If the checkbox is unchecked then the value from the hidden input will be send in the request.

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

2 Comments

Thanks for the answer! That's really dumb, though. If no checkbox value was sent in the request, why can't you assume it was unchecked? If for whatever reason the visibility of the checkbox was conditional, and that was actually relevant to your logic (I can't think of any reason why it would be), why couldn't you use that same condition on the subsequent POST? This really rubs me the wrong way; it's messing up my CSS adjacent sibling selector on checkboxes (to style their labels differently) because now I have this hidden field that is only useful in 0.5% of scenarios... Lame.
And, I think they got the default values wrong! I believe checkboxes come through as "on", not "true".

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.