表单提交前MVC不引人注意的验证

时间:2013-01-09 21:45:46

标签: asp.net-mvc unobtrusive-validation

我有以下型号:

public class PersonListModel
{
   ....

    [Required(ErrorMessage=AppConstants.MustSelectRecordToAttachMessage)]
    public String SelectedPersonId { get; set; }
}

和以下观点:

@using (Html.BeginForm("Attach", "Person", FormMethod.Post, new { @id = attachRecordFormId, targetDivId = personListId, @class = "inlineForm" }))
{
    .....

    @Html.HiddenFor(x => x.SelectedPersonId);

    .....

   <br />@Html.ValidationMessageFor(x => x.SelectedPersonId)
}

隐藏的SelectedPersonId字段通过一些javascript填充,该javascript挂钩到我页面上某个元素的keyup事件。

我的问题是所需的验证消息会立即显示此部分视图,而不仅仅是在提交表单时。在通过Ajax帖子再次呈现局部视图后,它也会再次显示。

我有非常相似的观点,没有出现这个问题,但有2个观点(包括上面的观点)确实出现了这个问题。我经历了一个消除过程,试图弄清楚正常工作的视图和表现出这种错误行为的视图之间有什么不同,但是我无法找到问题的原因。

我认为在加载问题视图时会引发不引人注意的验证。我该如何追踪这个?

1 个答案:

答案 0 :(得分:2)

  

我的问题是所需的验证消息会立即显示此部分视图

如果显示视图的控制器操作(包含部分)将视图模型作为参数,则可能发生这种情况:

public ActionResult Display(MyViewModel model)
{
    ... if this action is called with a GET request and you have missed
        to pass a value for the "SelectedPersonId" query string parameter 
        you will get a validation error in the corresponding view

    return View(model);
}

发生这种情况的原因是因为您的行为是采用模型=&gt;在尝试填充视图模型时,默认模型绑定器正在起作用,当它尝试为SelectedPersonId属性设置值时,如果请求中没有相应的值,它将自动向模型状态添加验证错误,因为model属性使用[Required]属性进行修饰。

  

在通过Ajax帖子再次呈现局部视图后,它也会再次显示。

这是正常的,如果目标POST操作将您的视图模型作为参数并呈现部分,则可能发生这种情况:

[HttpPost]
public ActionResult Process(MyViewModel model)
{
    ... if this action is called with a POST request and you have missed
        to pass a value for the "SelectedPersonId" form parameter 
        you will get a validation error in the corresponding partial view

    return PartialView(model);
}
相关问题