页面加载时的验证触发

页面加载时的验证触发

本文介绍了页面加载时的验证触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我有一个使用Razor View引擎的MVC 3应用程序.我启用了不打扰的验证.问题是由于某种原因,在页面加载时,我的编辑视图"显示必需字段的错误(即使这些字段具有值).还有其他人碰到这个吗?有解决这个问题的建议吗?谢谢.

Currently, I have an MVC 3 app using the Razor View engine. I have unobtrusive validation enabled. The problem is that for some reason, on page load, my Edit View is displaying errors for required fields (even though the fields have a value). Has anyone else ran into this? Any suggestions for resolving this? Thanks.

有问题的样本字段:

    <div class="full">
            <label>Description:</label>
            @Html.EditorFor(x=>x.Description, new{@class="super-textarea"})
            @Html.ValidationMessageFor(x => x.Description)

        </div>

模型上的数据注释:

     [Required, DataType(DataType.MultilineText)]
    public virtual string Description { get; set; }

启用WebConfig的设置:

WebConfig enabled settings:

     <add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

当然还有正确的jquery文件....

And of course the proper jquery files....

推荐答案

好.找到了问题.由于尝试进行模型绑定,因此发生了验证.之所以发生这种情况,是因为我们的Get Method看起来像这样.

Ok. Found the problem. Validation was happening due to Model binding attempting to take place. This was happening because our Get Method looks like this.

    [HttpGet, RequestedObjectFilter]
    public virtual ViewResult Edit(TKey id, T requestedObject)
    {

        return View(requestedObject);
    }

.NET MVC的一个功能是,每当在ViewResult的方法签名"中将引用值作为参数传递时,都会触发ModelBinding,从而触发验证.之所以将对象传递给我们的方法,是因为我们的RequestedObjectFilter将从抽象的存储库中获取相关实体,然后通过ActionParameters属性将其传递给此方法.我们重构了RequestedObjectFilter来设置ViewModel,从而允许我们从方法中删除参数,从而解决了问题.现在我们的方法如下:

A feature of .NET MVC is that anytime a reference value is passed as a parameter in the Method Signature of a ViewResult, ModelBinding is triggered, which in turn fires off validation. The reason that we were passing in the object to our method was due to our RequestedObjectFilter which would fetch the related entity from our abstracted repository, and pass it in to this method via the ActionParameters property. We refactored our RequestedObjectFilter to set the ViewModel instead, allowing us to remove the parameter from the method, thus solving the problem. Now our method looks like this:

     [HttpGet, RequestedObjectFilter]
    public virtual ViewResult Edit(TKey id)
    {

        return View();
    }

这篇关于页面加载时的验证触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 05:57