JQuery通过Ajax提交表单并返回结果

  如下:

  1:非Ajax

  前台:

JQuery通过Ajax提交表单并返回结果

  对应后台:

JQuery通过Ajax提交表单并返回结果

  2:JQuery之Ajax

  在介绍使用JQuery提交表单前,我们需要首先引用jquery.form.js,它来自于http://www.malsup.com/jquery/form/,至此,我们需要引用的JS文件有:

JQuery通过Ajax提交表单并返回结果

  功能要求:Ajax提交表单,在控制器HelloWorld4Controller中处理请求,并返回若干数据,数据格式为JSON。

  首先,我们假设返回的JSON实体为:

  

复制代码 代码如下:

  public class LoginResultDTO

  {

  public bool Success { get; set; }

  public string Message { get; set; }

  public string ReturnUrl { get; set; }

  }

  控制器部分的代码为:

  

复制代码 代码如下:

  public class HelloWorld4Controller : Controller

  {

  public ActionResult Index()

  {

  if (Request.IsAjaxRequest())

  {

  string str1 = Request.Form["Text33"];

  string str2 = Request.Form["Text44"];

  return Json(new MvcApplication5.Controllers.HelloWorld3Controller.LoginResultDTO { Success = true, Message = str1 + str2, ReturnUrl = "SomeUrl" });

  }

  else

  {

  return View();

  }

  }

  }

  

  上面的代码告诉我们,如果我们想要返回别的实体,也是很方便的的。

  前台部分代码:

JQuery通过Ajax提交表单并返回结果

  如果按钮不使用submit,而是button,则上图代码换成如下形式:

JQuery通过Ajax提交表单并返回结果

  源码下载:MvcApplication5.zip