0

I have a form that I would like to endow with wonderful Ajax-submission goodness

@using(Html.BeginForm()) {
  ...
}

I changed Html.BeginForm() to Ajax.BeginForm() but am not quite clear about what to do on the server side.

Previously, I used to do something like this:

[HttpPost]
public ActionResult EditMyStuff(MyViewModel vm) {
  if(!ModelState.IsValid)
    return View(vm);

  // save stuff
  return RedirectToAction("Index");         
}

And this is stuff I want to retain if the client has javascript disabled but if the form is submitted via Ajax clearly this is not what I want - I want any errors to appear in the validation summary on error or an "Your changes have been saved" message on success.

What is the standard way of doing this?

1 Answer 1

2

You have to add an If clause for the Ajax Request

if (Request.IsAjaxRequest()) 
{
    // Return PartialView or Json
}
else 
{
    // Normal response
}
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome, is there a built-in way to return my ModelState errors then?
What I normally do is to add the error message on the ViewData dictionary (ViewBag if you're using ASP.NET MVC3)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.