Scenario
Your fields for your web page is ready. Now, you're asked to make use of a checkbox for the age option instead of entering the age, as shown:
Aim
Make use of a checkbox for the age option instead of entering the age.
Steps for completion
- Use the following code to change your view:
Go to https://goo.gl/WtzFSg to access the code.
@model Activity3C1.Models.Person
@if (ViewBag.Message != null)
{
<b>@ViewBag.Message</b>
}
@{
}
@using (Html.BeginForm("ValidateAge", "Home",
FormMethod.Post))
{
<table>
<tr>
<td>@Html.LabelFor(Model => Model.Name) </td>
<td>@Html.TextBoxFor(Model => Model.Name) </td>
</tr>
…
…
</table>
}
- Change your action using the following code:
Go to https://goo.gl/Fqkrg3 to access the code.
[HttpPost]
public IActionResult ValidateAge(Person person1)
{
if(Convert.ToBoolean(
Request.Form["OlderThan18"][0]))
{
ViewData["OlderThan18"] = true;
ViewBag.Message = "You are eligible to Vote!";
}
else
{
ViewBag.Message = "Sorry.You are not old enough to vote!";
}
return View();
}
The reason we use Request.Form["OlderThan18"][0] is that, by default, the checkbox helper creates a hidden form, meaning that we get a false value if the checkbox is unchecked. As HTML, by default, does not send a value for unchecked checkboxes, we also fill our ViewBag so that we can retain our value.