5

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?

Roman Mazur
  • 512
  • 6
  • 17
  • You can take advantage of unobstrusive validation with jquery. Check out this link: http://robdmoore.id.au/blog/2012/04/27/unobtrusive-validation-in-asp-net-mvc-3-and-4/ – JoonasL Aug 20 '12 at 14:26
  • @JoonasL I am afraid that it does not solve my problem. As I said, I know how to validate my model. The problem is about displaying the validation messages as they come from server by Ajax. – Roman Mazur Aug 20 '12 at 14:51
  • Oh, well then as you get back the ajax result that says the validation has failed. Then manually display the error message for the jquery validation. There is no simpler way. See this question for manually triggering error: http://stackoverflow.com/questions/1479255/how-to-manually-trigger-validation-with-jquery-validate – JoonasL Aug 20 '12 at 16:19
  • "Processed on server" and "displayed immediately by client" are kinda conflicting requirements. – anaximander Mar 26 '13 at 13:31
  • @anaximander You are right, there was a problem with my expression. I wanted to say that I need the answer to be displayed without page refresh. – Roman Mazur Sep 05 '13 at 13:27

1 Answers1

3

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

Andras Toth
  • 576
  • 4
  • 11