处理MVC3中的验证 - 每个复选框组必须选中一个复选框

时间:2012-04-06 22:21:58

标签: jquery asp.net-mvc-3 validation

[标题应该说“每个问题必须选中一个复选框”,但SO不允许标题中的“问题”一词]

简单的Q / A表格。举一个例子,有7个问题。在POST时,我的控制器操作需要IEnumerable<AssessmentQuestionsModel>。我的AssessmentQuestionsModel实现IValidatableObject,我的验证方法如下:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if (this.assessmentAnswers.Where(e => e.userAnswer == true).Count() == 0)
    {
        yield return new ValidationResult("You must select at least one answer for every question");
        yield break;
    }
}

这在视图级别工作正常 - 它返回该错误消息并将其显示在验证摘要中。问题是,它返回7次,每个问题一次。目前我正在使用jQuery来评估验证摘要UL&amp;删除重复项,但这似乎是一个黑客。我做错了什么?

由于

[编辑 - 测试验证过载]

事实上,以下是两次被召唤。但是,它们未分组,仍会显示多个验证错误。

if (this.assessmentAnswers.Where(e => e.UserAnswer== true).Count() == 0)
{
    yield return new ValidationResult("You must select at least one answer for every question", new List<string>() { "NoAnswerMarked" });
    yield break;
}

[编辑 - 查看信息]

@using System.Linq
@using System.Collections.Generic
@model IList<Academy.AssessmentQuestionsModel>

@{
    ViewBag.Title = "TakeAssessment";
    ViewBag.PageID = "TakeAssessment";
}
@section TitleBar {
    <span>
    @if(ViewBag.Status == "questions") {    
        <text>Take Assessment</text>
    } else {
        <text>Assessment Response</text>
    }
    </span>
}
@section JS {
<script type="text/javascript">
    $(function () {
        if ($(".validation-summary-errors li:contains('You must select at least one answer for every question')").length > 0) {
            $(".validation-summary-errors ul")
                .find("li:contains('You must select at least one answer for every question')")
                .remove()
                .end()
                .append("<li>You must select at least one answer for every question</li>");
        }
        $("#asubmit").click(function (e) {
            var hasErrors = false;
            $(".newAnswerWrapper").each(function () {
                if ($(this).find('input[type="checkbox"]:visible:checked').length == 0) {
                    e.preventDefault();
                    hasErrors = true;
                    return false;
                }
            });
            if (hasErrors) {
                $(".validation-summary-valid").find("ul").append("<li>You must select at least one answer for every question</li>").end().show();
            } else {
                $(".validation-summary-errors").find("li:contains('You must select at least one answer for every question'')").remove().end().hide();
            }
        });
    });
</script>
}
@using (Html.BeginForm())
{
    @Html.ValidationSummary(false)
<fieldset>
    <legend></legend>
    <div class="takeAssessment">
    @if(!string.IsNullOrEmpty(ViewBag.AssessmentInstructions)) {
        <h4>Instructions</h4>
        <p>@ViewBag.AssessmentInstructions</p>
    }
    @{
    int questionCount = 0;
    int totalQuestions = Model.Count();

    @Html.Hidden("ModuleID", (int)ViewBag.ModuleID)
    for (var i = 0; i < Model.Count; i++)
    {

        @Html.HiddenFor(m => m[i].questionDescription)
            <div class="newQuestionWrapper">
                    <h4>Question @(i + 1) of @totalQuestions</h4>
                    @Html.HiddenFor(m => m[i].assessmentID)
                    @Html.HiddenFor(m => m[i].assessmentQuestionID)
                    <p class="questionDescription">@Model[i].questionDescription</p>
                    <div class="newAnswerWrapper"></div>

                <div class="newAnswerWrapper">
                    <div class="answerHeader">
                        <p class="correct">Select</p><p class="answers">Answer(s)</p>
                    </div>

                 @for (var j = 0; j < Model[i].assessmentAnswers.Count(); j++)
                 {
                    @Html.HiddenFor(m => m[i].assessmentAnswers[j].assessmentAnswerID)
                    @Html.HiddenFor(m => m[i].assessmentAnswers[j].assessmentQuestionID)
                    @Html.HiddenFor(m => m[i].assessmentAnswers[j].assessmentAnswer)

                     if (ViewBag.Status == "questions")
                     {          
                         <div class="answerRow">
                            <span class="isAnswer first">@Html.CheckBoxFor(m => m[i].assessmentAnswers[j].userAnswer)</span>
                            <span class="answerDisplay">@Html.DisplayFor(m => m[i].assessmentAnswers[j].assessmentAnswer)</span>
                            @Html.HiddenFor(m => m[i].assessmentAnswers[j].isAnswer)
                            <div class="clear"></div>
                         </div>
                     }
                     else
                     {
                        <div class="answerRow">
                            @{
                                string cls = Model[i].assessmentAnswers[j].isAnswer ? "correct" : "incorrect";
                            }
                            <span class="isAnswer first">@Html.CheckBoxFor(m => m[i].assessmentAnswers[j].userAnswer, new { @disabled = "disabled" })</span>
                            <span class="answerDisplay" style="width: 510px !important;">@Html.DisplayFor(m => m[i].assessmentAnswers[j].assessmentAnswer)</span>
                            <span class="isAnswer"><span class="@cls">@Html.DisplayFor(m => m[i].assessmentAnswers[j].isAnswer)</span></span>

                            <div class="clear"></div>
                        </div>
                     }
                     <div class="clear"></div>
                 }

              </div>

    <div class="clear"></div>
            </div>
    }
}

    <div class="clear"></div>
    </div>
    @if (ViewBag.Status == "questions")
    {
    <input type="submit" id="submit" value="Submit Assessment" class="redButton197x38" />
    }
</fieldset>
}
<p>
    @Html.ActionLink("Back to Module", "Learn", new { id = ViewBag.ModuleID }, new { @class = "redButton197x38" })
</p>

1 个答案:

答案 0 :(得分:0)

我一直在考虑你的问题,我认为问题比我想的要简单得多,有一个ValidationResult类的重载构造函数,它要求传入成员名称,如果你传入相同的密钥(new List(){&#34; QuestionError&#34;}))这里它应该对它们进行分组,只显示一个结果。