Validation Firing on Page Load

这一生的挚爱 提交于 2019-12-07 04:01:13

问题


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.

Sample Field with problem:

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

        </div>

Data Annotations on Model:

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

WebConfig enabled settings:

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

And of course the proper jquery files....


回答1:


You can also clear the errors from the ModelState

ModelState.Clear();



回答2:


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);
    }

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();
    }


来源:https://stackoverflow.com/questions/9832742/validation-firing-on-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!