标签:style blog http io ar os sp for java
曾经学习过AJAX,不是特别的熟悉,这次利用学习MVC的机会,好好的体验了一把,非常感谢《MVC开发实战》这本书,看了有两三遍,才算对MVC整个运行的机制有了一定的了解,下面来分享下我们经常在开发时用到到的异步表单的操作。
DEMO
1.VIEW
<span style="font-size:18px;">@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript">
function suc(resText) {
//
alert(resText);
}
function err(xhr) {
//失败时执行操作,参数为ajaxrequest对象
alert(xhr.readyState);
}
</script>
<style type="text/css">
#imgLoad {
display: none;
}
</style>
</head>
<body>
@Ajax.ActionLink("连接文字", "GetDate", new AjaxOptions()
{
HttpMethod = "post",
//更新的控件id
UpdateTargetId = "contDiv",
//更新方式
InsertionMode = InsertionMode.Replace
})
<div id="contDiv" style="border:1px solid #0094ff; width:400px;">我很好</div>
<h1>异步表单:</h1>
@using (Ajax.BeginForm("GetDat", "Home", new AjaxOptions()
{
//提交请求的方法
HttpMethod = "post",
//成功时执行的异步函数
OnSuccess = "suc",
OnFailure = "err",
//请求时加载的图片
LoadingElementId = "imgLoad"
}))
{
<input type="text" name="txtName" />
<input type="submit" />
<div id="imgLoad">加载中~~~</div>
}
</body>
</html>
</span>
2.Controller
<span style="font-size:18px;"> /// <summary>
/// 控制器
/// </summary>
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
/// <summary>
/// 异步请求的方法,返回的是时间的内容对象
/// </summary>
/// <returns></returns>
public ActionResult GetDate()
{
System.Threading.Thread.Sleep(200);
return Content(DateTime.Now.ToString());
}
}</span>
2.结果显示
3.代码分析
1.异步连接
@Ajax.ActionLink()方法,经常用到的几个参数在DEMO中已经体现,并且已经加入了详细的注释,主要用来实现异步连接的操作。并且可以对返回的内容进行操作。
2.异步表单
Ajax.BeginForm()方法,不得不说,在MVC中以后会经常用到这个方法,同上一样,Demo有详细的注释,不再多说。比如我们在做一个登录功能的时候,就可以采取异步表单。通过提交表单到后台,然后把返回的登录结果在现实到View中,挺方便的。
标签:style blog http io ar os sp for java
原文地址:http://blog.csdn.net/luckyzhoustar/article/details/41850829