Razor ViewEngine HTML.Checkbox method creates a hi

2019-01-09 11:51发布

This question already has an answer here:

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?

3条回答
【Aperson】
2楼-- · 2019-01-09 12:12

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

bool myCheckBoxValue = Server.HtmlEncode(Request.QueryString["MyCheckBoxValue"]).Contains("true");
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-09 12:15

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
查看更多
我想做一个坏孩纸
4楼-- · 2019-01-09 12:25

ericvg explained it well.

The manual approach is this:

bool IsDefault = (Request.Form["IsDefault"] != "false");
查看更多
登录 后发表回答