Reputation: 512
I am using @Ajax.BeginForm
helper method, which submits form data to the server by Ajax. When the data arrive to the server, some server side validation is processed and final result is passed back to the browser.
My problem is, I want the errors to be displayed without page refresh. I have found plenty of questions based on this but they are old. I am wondering if there is some new way how to achieve this. The best way I have found so far is to process the result using jQuery. But maybe in new MVC4 there is some built in functionality how to achieve this problem in a better way?
Upvotes: 5
Views: 5172
Reputation: 628
Your view should look similar to this:
<div id="update-this">
@using (Ajax.BeginForm("YourAction", new AjaxOptions { UpdateTargetId = 'update-this' }))
{
}
</div>
Also use @Html.ValidationMessageFor(model => model.someField)
next to your fields to display the error message.
On server side return a partial view if there was any error:
public ActionResult YourAction(YourModel yourmodel)
{
if (ModelState.IsValid)
{
// Do what is needed if the data is valid and return something
}
return PartialView("DisplayPartial", yourmodel);
}
And use Data Annotations on your model to make it work. (Tutorial here.)
Upvotes: 3