I have some checkboxes that are required to be checked before the user can go to the next page. What is the best way to display a validation message?
View:
@Html.CheckBox("terms_eligibility")
@Html.CheckBox("terms_accurate")
@Html.CheckBox("terms_identity_release")
@Html.CheckBox("terms_score_release")
Controller:
[HttpPost]
public ActionResult Review(ReviewModel model)
{
// Make sure all Terms & Conditions checkboxes are checked
var termsEligibility = Request.Form.GetValues("terms_eligibility")[0];
var termsAccurate = Request.Form.GetValues("terms_accurate")[0];
var termsIdentityRelease = Request.Form.GetValues("terms_identity_release")[0];
var termsScoreRelease = Request.Form.GetValues("terms_score_release")[0];
if (termsEligibility == "true" && termsAccurate == "true" &&
termsIdentityRelease == "true" && termsScoreRelease == "true")
{
return RedirectToAction("CheckOut","Financial");
}
return null;
}
EDIT,
I made the suggested changes. Now how do i get the same page to display with error messages?
I changes the attributes in the model to this
[RequiredToBeTrue(ErrorMessage = "*")]
here’s the conroller
[HttpPost]
public ActionResult Review(ReviewModel model)
{
if(ModelState.IsValid)
{
return RedirectToAction("CheckOut", "Financial");
}
return RedirectToAction("Review");
}
I’d recommend you using a view model and a custom validation attribute:
and the view model:
and the view will of course be strongly typed to the view model:
and finally your controller action will take the view model as parameter:
Notice that things like
Request.Form.GetValues("terms_eligibility")[0];andtermsEligibility == "true"are really not the kind of code you would like to see in a properly written application.