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 に答える