转摘:Aspnet mvc Html.Checkbox 处理
This post will explain how to get the value of a checkbox when a form is posted within the world of ASP.NET MVC. This post will explain this approach by first presenting a common problem and then showing you the recommended solution. You can just jump to the solution by clicking here.
A lot of times, you will ask a user to “sign up” or “register” to access your web application. Sometimes, this process will involve asking a user to agree to the terms of the site. This task usually relies on the user checking a checkbox stating that they agree to be a nice user. For instance, you can see an example of one such registration page here.
After a user has agreed, and decided to proceed, you should make sure they
checked the checkbox on the server side. The reason for this is to prevent
malicious developers from attacking your site. Regardless, if you are using
ASP.NET MVC, you may be surprised to learn that getting the value of a checkbox
is a little different from what you may be expecting. For instance, imagine you
have the following HTML page defined:
<html
xmlns=”http://www.w3.org/1999/xhtml” >
<head><title>Check
Test</title></head>
<body><form action=”/”
method=”post”>
<%= Html.CheckBox(”chkHuman”, false)%> Are you
human?<br />
<input type=”submit” value=”Move Along”
/>
</form></body>
</html>
Now imagine that when the user clicks the “Move Along” button, the following
action is triggered:
[AcceptVerbs(HttpVerbs.Post)]
public
ActionResult Index(FormCollection formValues)
{
string value =
formValues["chkHuman"];
return View();
}
If the user checks the checkbox, and this action gets executed, you will notice the “value” variable will be set to “true,false”. If the checkbox was not selected, the “value” variable will simply be “false”. While you could just check the length, or manually parse the value, there is a more elegant solution.
The recommended approach would be to write your code as follows:
[AcceptVerbs(HttpVerbs.Post)]
public
ActionResult Index(FormCollection formValues)
{
bool isChecked =
false;
if (Boolean.TryParse(Request.Form.GetValues(”chkHuman”)[0], out
isChecked) == false)
ModelState.AddModelError(”chkHuman”, “Nice
try.”);
return RedirectToAction(”Index”);
}
In this approach, we are relying on the Request.Form object. By indexing the first element of the value returned by the GetValues method, we will get either “true” or “false”. This can then be easily converted to a bool. The fact that the value can easily be converted to a bool is what makes it the recommended approach.