MVC是不能拖放控件的(至少到目前为止我这么认为),所以Ajax就显得很是重要了。
前几篇的jQuery与Ajax如果理解了,那很容易就能切换到MVC模式使用。虽然实际情况下,我是为了完成某些功能,直接就先应用MVC模式下的jQuery与Ajax,也就是这一篇和下一篇内容,当时只是知道大概是怎么回事然后模范一些样例用着而已(现在也差不多,只是比较熟练~)。
(我的新浪微博:@chen文哲http://weibo.com/u/2448939884欢迎程序员互粉,转载文章请保留本博客地址:http://blog.csdn.net/wowkk 欢迎交流^_^)
一:传统方式
新建一个Ajax控制器
public ActionResult Index()
{
//新建Index视图
return View();
}
public ActionResult GetTime()
{
return Content(DateTime.Now.ToString());
}
Index视图:
<head runat="server">
<title>Index</title>
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#btGetDateNowJQ").click(function () {
$.ajax({
url: "/Ajax/GetTime",
async: true, //默认true为异步,false为同步(模态对话框的形式)
data: "",
type: "get",
success: function (data) {
alert(data);
}
});
});
});
</script>
</head>
<body>
<div>
<input type="button" value="获取当前时间JQ" id="btGetDateNowJQ" />
</div>
</body>
二:MVC专用
视图
<head runat="server">
<title>Index</title>
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<%--下面两行是专用脚本--%>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
$(function () {
$("#loading").css("display", "none"); //隐藏改DIV内的内容
});
function myJS() {
alert("ok!");
}
</script>
</head>
<body>
<%using (Ajax.BeginForm("GetTime", new AjaxOptions()
{
Confirm="确定?",
HttpMethod = "post",
UpdateTargetId = "myDiv", //返回数据更新到指定DIV
InsertionMode=InsertionMode.Replace, //类型为替换(另有追加等)
OnSuccess="myJS", //执行成功后可以再执行某JS函数
LoadingElementId="loading" //执行过程中显示某DIV内内容
}))
{%>
<input type="submit" value="提交?" />
<% } %>
<div id="myDiv">
</div>
<div id="loading">
加载中!
</div>
</body>
控制器:
public ActionResult GetTime()
{
Thread.Sleep(2000);
return Content(DateTime.Now.ToString());
}