Razor ViewEngine HTML.Checkbox method creates a hi

2019-01-09 11:42发布

问题:

This question already has an answer here:

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

I have written the below code on my view page;

@Html.CheckBox("ChxName",true)

and I got the following result;

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

why is there a input element named as the same with checkbox?

回答1:

Unchecked checkboxes are not posted, so the hidden field (set as false) allows the model binding to still work.

Look at Request.Form on the post back. If the checkbox is checked, you'll see:

ChxName=true&ChxName=false

The model binder uses the first value.

and, if the box isn't checked, you'll see:

ChxName=false


回答2:

ericvg explained it well.

The manual approach is this:

bool IsDefault = (Request.Form["IsDefault"] != "false");


回答3:

Or use Contains("true") which I find a bit neater...

bool myCheckBoxValue = Server.HtmlEncode(Request.QueryString["MyCheckBoxValue"]).Contains("true");