MVC中的异步提交有两种方法,一种是JQuery方式,一种是MVC中自带的Ajax.BeginForm方式,两种都可以实现异步提交与刷新
JQuery.Ajax
Controllers代码
public ActionResult Index() { return View(); } public ActionResult GetDate() { //获取参数信息 string id = Request["id"].ToString(); string name = Request["name"].ToString(); return Content("用户:"+name+" 时间:"+ DateTime.Now.ToString()); }
View页面代码
@{ ViewBag.Title = "Index"; } <html> <head> <Meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="~/Scripts/jquery-1.8.2.js"></script> @*使用JQuery的异步方式获取后台的信息*@ <script type="text/javascript"> $(function () { $("#btnJQ").click(function () { //从后台获取时间 $.ajax({ url: "/Ajax/GetDate",//请求地址 type: "Get",//请求的类型 success: function (data) { //成功后的回调函数 alert(data); },data: "id=1&name=信息"//传递的数据 }); }); }); </script> </head> <body> <h2>Ajax页面</h2> <div> <input type="button" id="btnJQ" value="显示后台返回的数据" /> </div> </body> </html>
Ajax.BeginForm
Controllers代码
public ActionResult MicrosoftAjax() { return View(); } public ActionResult ReData() { //获取参数信息 string sname = Request["UserName"].ToString(); //让网站睡眠1秒钟 //System.Threading.Thread.Sleep(1000); return Content("用户名:" + sname); }
View页面代码
<!DOCTYPE html> <html> <head> <Meta name="viewport" content="width=device-width" /> <title>MicrosoftAjax</title> <script src="~/Scripts/jquery-1.8.2.js"></script> <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script> <script type="text/javascript"> function afterSuccess(data) { //数据执行成功后,触发的事件 alert(data); } </script> </head> <body> <div> @using (Ajax.BeginForm("ReData","Ajax",new AjaxOptions() { Confirm = "您是否要提交吗?",HttpMethod = "Post",InsertionMode = InsertionMode.Replace,UpdateTargetId = "result",OnSuccess = "afterSuccess" })) { <div> 用户名:<input type="text" name="UserName" /><br /> 密码:<input type="text" name="Pwd" /><br /> <input type="submit" value="提交" /> </div> } <div id="result"> 这个是要显示结果的div </div> </div> </body> </html>