简体   繁体   中英

ASP.Net MVC3 - Properly handle Ajax form submission on the server side

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?

You have to add an If clause for the Ajax Request

if (Request.IsAjaxRequest()) 
{
    // Return PartialView or Json
}
else 
{
    // Normal response
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM