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....
You can also clear the errors from the ModelState
ModelState.Clear();
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With