我有一些复选框需要在用户转到下一页之前进行检查。显示验证消息的最佳方法是什么?
查看:
@Html.CheckBox("terms_eligibility")
@Html.CheckBox("terms_accurate")
@Html.CheckBox("terms_identity_release")
@Html.CheckBox("terms_score_release")
控制器:
[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,
我做了建议的更改。现在我如何使用错误消息显示同一页面?
我将模型中的属性更改为此
[RequiredToBeTrue(ErrorMessage = "*")]
这是控制者
[HttpPost]
public ActionResult Review(ReviewModel model)
{
if(ModelState.IsValid)
{
return RedirectToAction("CheckOut", "Financial");
}
return RedirectToAction("Review");
}
答案 0 :(得分:3)
我建议您使用视图模型和自定义验证属性:
public class RequiredToBeTrueAttribute : RequiredAttribute
{
public override bool IsValid(object value)
{
return value != null && (bool)value;
}
}
和视图模型:
public class MyViewModel
{
[RequiredToBeTrue]
public bool TermsEligibility { get; set; }
[RequiredToBeTrue]
public bool TermsAccurate { get; set; }
[RequiredToBeTrue]
public bool TermsIdentityRelease { get; set; }
[RequiredToBeTrue]
public bool TermsScoreRelease { get; set; }
... some other properties that are used in your view
}
,视图当然会强烈输入视图模型:
@model MyViewModel
@Html.ValidationSummary(false)
@using (Html.BeginForm())
{
@Html.CheckBoxFor(x => x.TermsEligibility)
@Html.CheckBoxFor(x => x.TermsAccurate)
@Html.CheckBoxFor(x => x.TermsIdentityRelease)
@Html.CheckBoxFor(x => x.TermsScoreRelease)
...
<button type="submit">OK</button>
}
最后你的控制器动作将视图模型作为参数:
[HttpPost]
public ActionResult Review(MyViewModel model)
{
if (!ModelState.IsValid)
{
// there were validation errors => redisplay the same view
// so that the user could fix them
return View(model);
}
// at this stage we know that validation succeeded =>
// we could proceed in processing the data and redirecting
...
return RedirectToAction("CheckOut", "Financial");
}
请注意,Request.Form.GetValues("terms_eligibility")[0];
和termsEligibility == "true"
之类的内容实际上并不是您希望在正确编写的应用程序中看到的代码类型。