2

在用户可以转到下一页之前,我需要检查一些复选框。显示验证消息的最佳方式是什么?

看法:

@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;
}

编辑,

我做了建议的更改。现在我如何让同一页面显示错误消息?

我将模型中的属性更改为此

 [RequiredToBeTrue(ErrorMessage = "*")]

这是控制器

[HttpPost]
public ActionResult Review(ReviewModel model)
{


    if(ModelState.IsValid)
    {
        return RedirectToAction("CheckOut", "Financial");
    }

    return RedirectToAction("Review");
}
4

1 回答 1

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"的内容实际上并不是您希望在正确编写的应用程序中看到的那种代码。

于 2012-08-07T16:14:22.827 回答