简体   繁体   English

ASP.Net MVC3 - 在服务器端正确处理 Ajax 表单提交

[英]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我有一个表单,我想赋予它美妙的 Ajax 提交功能

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

I changed Html.BeginForm() to Ajax.BeginForm() but am not quite clear about what to do on the server side.我将Html.BeginForm()更改为Ajax.BeginForm()但不太清楚在服务器端做什么。

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.如果客户端禁用了 javascript 但如果通过 Ajax 提交表单显然这不是我想要的 - 我希望任何错误出现在错误的验证摘要中或“您的更改已保存“成功的消息。

What is the standard way of doing this?这样做的标准方法是什么?

You have to add an If clause for the Ajax Request您必须为 Ajax 请求添加 If 子句

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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