Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation Firing on Page Load

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....

like image 718
user1287132 Avatar asked Mar 23 '12 00:03

user1287132


2 Answers

You can also clear the errors from the ModelState

ModelState.Clear();
like image 77
Aaron Hoffman Avatar answered Oct 29 '22 13:10

Aaron Hoffman


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();
    }
like image 11
user1287132 Avatar answered Oct 29 '22 13:10

user1287132