开发者

how to check if a checkbox is checked, convert tobool fails since its lower case 'false'

I am doing:

convert.t开发者_JAVA技巧oboolean(request.form["mycheckbox"]

but since the value is 'false', it doesn't seem to cast to boolean.

What should I do?

I don't like checking for == "false" and then converting to boolean.

is there a cleaner way?

Update

All I am doing is:

if (Convert.ToBoolean(request.Form["somecheckbox"]))
{


}


Looks like the Html.Checkbox helper creates a checkbox and a hidden field, both with the name that you provide ("mycheckbox"). The hidden field appears to have the original value of the checkbox (though I could be off on what, exactly, its purpose is).

I would say that if you're getting values manually out of the Request collection, you should be creating your controls manually, too, instead of using Html.Checkbox and similar helpers, which may add other stuff that the framework knows about but you don't.

The other alternative would be to let the framework bind that value, rather than getting it manually.


Convert.ToBoolean is to be used for "0" and "1"

You can also try Boolean.Parse for "true" and "false"


bool isChecked = false;
if (request.form["mycheckbox"] != null)
{
     isChecked = (request.form["mycheckbox"]).checked;
}


bool b = request.form["mycheckbox"] != null && request.form["mycheckbox"] == "true";
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜