Asp.net MVC 3远程验证问题

时间:2012-03-13 15:51:46

标签: asp.net-mvc-3 model-view-controller unobtrusive-validation jquery-validate

每次远程验证在我的表单上触发时,我都会收到以下网址...而不是我的预期: http://localhost:13927/Validation/ValidateAnswer?%5B0%5D.Episodes%5B0%5D.Questions%5B0%5D.Answers%5B0%5D.AnswerText=undefined&%5B0%5D.Episodes%5B0%5D.Questions%5B0%5D.Answers%5B0%5D.Id=undefined

控制器是正确的。动作是正确的,但参数不是我的预期。关于如何纠正这个问题的任何想法?验证操作的签名是public JsonResult ValidateAnswer(string answerText, int id).

以下是模型:

public class Answer
{
    public int Id { get; set; }
    [Required(ErrorMessage = "Please enter an answer.")]
    [Remote("ValidateAnswer", "Validation", AdditionalFields = "Id")]
    public string AnswerText { get; set; }
}

这是Page:

@using (Html.BeginForm("/", "Home", FormMethod.Post, new {id="frm"}))
    {
        for (var p = 0; p < Model.Count; p++)
        {
            <div class="hidden questions" id="@Model[p].Id">
                @for (var i = 0; i < Model[p].Episodes.Count; i++)
                {
                    <div class="even" style="margin-top: 15px; padding: 15px;">
                        @Html.EditorFor(model => model[p].Episodes[i])
                    </div>
                }
            </div>
        }
    }

以下是编辑引用:

<h3 style="margin: 0; margin-bottom: 15px;">@Model.EpisodeType, which started on @Model.StartDate and ended on @Model.EndDate</h3>
@Html.HiddenFor(model=>model.Id)
@for (var i = 0; i < Model.Questions.Count; i++ )
{
    <p style="margin: 0; margin-bottom: 5px;">
        <span style="font-weight: bold; font-size: 1.1em">@Model.Questions[i].QuestionText</span><br/>
    </p>
    <p style="margin: 0; margin-bottom: 10px;">
        @{ var theClass = string.Concat("autocomplete", Model.Questions[i].IsYesNo ? "yesno" : Model.Questions[i].IsTime ? "time" : ""); }
        @Html.TextBoxFor(model=>model.Questions[i].Answers[0].AnswerText, new {@class=theClass, question=Model.Questions[i].Id.ToString()})
        @Html.ValidationMessageFor(model=>model.Questions[i].Answers[0].AnswerText)        
        @Html.HiddenFor(model => model.Questions[i].Id)
    </p>
}

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。最后,我将它追溯到jquery.validate.unobtrusive.js中的第309行:

return $(options.form).find(":input[name='" + paramName + "']").val();

这个jQuery调用返回0个对象,可能是因为它为(你的输入名称)过滤的名称包含方括号,这会混淆jQuery解析器。

你可以用以下代替它来修复它:

return $(options.form).find(":input[id='" + options.element.id + "']").val();

以上是按id过滤的,所以没有奇怪的字符来绊倒jQuery。