在 MVC 中实现异步操作有两种方法,一种是使用jQuery
的异步函数,另一种就是使用MVC的 AjaxHelper
注意:在行为详解中提到过,如果行为的返回对象为JsonResult 时,要使用get获取必须添加第二个参数-JsonRequestBehavior.AllowGet
.
注意:jQuery实现需要调用jquery文件
先编写控制器方法:
public ActionResult CalcAdd(int a, int b)
{
int sum = a + b;
return Content(sum.ToString());
}
添加视图,并通过自动装配来实现绑定和异步请求:
<script>
$(function() {
$('#btAdd').click(function() {
$.post(
'@Url.Action("CalcAdd","AjaxTest")',
$('#form1').serialize(),
function(msg) {
$('#sum').val(msg);
}
);
});
});
</script>
<div>
<form action="/" method="post" id="form1">
<input type="text" name="a" />+
<input type="text" name="b" />
<input type="button" id="btAdd" value="加" />
<input type="text" name="sum" id="sum" />
</form>
</div>
解释一下过程,就是:
通过浏览器jQuery发送post请求给AjaxTest/ CalcAdd
这个action,自动识别传送的name:a,b,并通过路由实现自动接收装配,经由控制器中的action的操作后,将结果异步返回给网页。
注意:AjaxHelper实现需要调用jquery.unobtrusive-ajax 文件,可以使用 NuGet 添加。
同样的,先写控制器:
public ActionResult CalcAdd1(int a, int b)
{
int sum = a + b;
var temp = new
{
Sum = sum
};
return Json(temp,JsonRequestBehavior.AllowGet);
}
注意,这里返回的对象是一个匿名对象,并使用Json()方法完成序列化。
视图部分,js实现一个回掉函数并给值
function Success(obj) {
$('#result').val(obj.Sum);
}
使用 AjaxHelper 创建一个Ajax表单:
@using (Ajax.BeginForm("CalcAdd1", "AjaxTest", new AjaxOptions()
{
OnSuccess = "Success"
}))
{
<input type="text" name="a" />
<span>+</span>
<input type = "text" name = "b" />
<input type = "submit" value = "=" />
<input type = "text" id = "result" />
}
表单提交后会使用前面创建的回掉函数并给值。