开发者

CheckBox in asp.net mvc

开发者 https://www.devze.com 2022-12-29 23:37 出处:网络
i have two options One <%= Html.CheckBox(\"postType\", false, new { @id = item.int_PostTypeId.ToString() })%>

i have two options

One

<%= Html.CheckBox("postType", false, new { @id = item.int_PostTypeId.ToString() })%>

Second

<input type="checkbox"  name="postType" value="<%= item.int_PostTypeId.ToString() %>

1st question: what is differenct between these two method of check box declaration.

2nd question:开发者_Go百科 and how can we get value of checked checkbox?


Use the Html.Checkbox (or even better the CheckBoxFor, in MVC2) if you use a model binder. It will handle the checkbox transparently to you, and you will read the boolean value on your model. It will render something more complicated than a checkbox (to avoid the problem which arises from the fact that an unchecked checkbox is not transmitted at all in a POST).

On the contrary, use the input if you retrieve the value via FormCollection: if you use the Html.Checkbox compound, you will receive something "strange" in the post (not the usual value, but a string with two testual values (like "true,false"). If you use the input, you just have to check if there exists that name in the post keys.


One major difference is that your are setting the "id" attribute of the HTML input (@ is used to denote the HTML tag attribute: @id, @class, etc.) in the first snippet and setting the "value" of the second...

You need to set the @id in both, so that you can retrieve the value easily in Javascript.

You didn't say in what context you wanted the value - whether client side via javascript or controller side via .NET.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号