Ajax-ActionLink与BeginForm
- 作用:
创建表单和指向控制器操作方法 - 调用:
1.搜索安装:
Microsoft.jQuery.Unobtrusive.Ajax.3.2.6
2.在视图头部引入:
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
3.通过@Ajax调用:
@Ajax.ActionLink
@Ajax.BeginForm
- ActionLink
可以创建一个具有异步行为的超链接,可以设置AjaxOptions对象的属性值
第一个参数是超链接文本,第二个参数是操作方法名称
举例:在前端视图里:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script>
function msg(data) {
alert(data);
$("#dshow").html(data);
}
</script>
</head>
<body>
@Ajax.ActionLink("获取时间新方法","GetDate","home",new AjaxOptions
{
Confirm = "确认提交嘛?",
HttpMethod = "post",
InsertionMode = InsertionMode.InsertAfter,
OnSuccess = "msg",
UpdateTargetId = "show"
})
获取时间:
<div id="show" style="width:300px;height:30px;border:1px dotted solid"></div>
</body>
</html>
写在后端控制器的GetDate方法,在上篇文章已经提到过。
- AjaxOptions
- BeginForm:
Ajax.BeginForm( new AjaxOpitions{//提交到当前页面
UpdateTargetID = "UserLogOnContainer",//异步更新模块ID
HttpMethod="Post",//提交方式为POST
OnSuccess =""
})
Ajax.BeginForm("action","controller",null new AjaxOpitions{//提交到指定控制器
UpdateTargetID = "UserLogOnContainer",//异步更新模块ID
HttpMethod="Post",//提交方式为POST
OnSuccess =""
})
例子:用BeginForm提交表单实现用户注册的功能
Index(注册页面):
<meta charset="utf-8">
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<body>
@using (Ajax.BeginForm("UserRegister", "Home", new AjaxOptions
{
Confirm = "确定注册吗?",
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
LoadingElementId = "loading",
UpdateTargetId = "show",
}))
{
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="UserName"/></td>
</tr>
<tr>
<td>密码:</td>
<td>
<input type="password" name="Password"/>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="注册"/></td>
</tr>
</table>
}
@*Loading标签用于加载效果,show标签用于展示ajax返回的数据:*@
<div id="loading">Loading</div>
<div id="show"></div>
</body>
前端result视图界面:
@{
ViewBag.Title = "result";
string name = ViewBag.name;
string password = ViewBag.pwd;
}
<div>
<h2>Result</h2>
<p>你注册的名称是:@name</p>
<p>你注册的密码是:@password</p>
</div>
在后台控制器部分:
public ActionResult result()
{
return View();
}
public ActionResult UserRegister(string UserName,string Password)
{
System.Threading.Thread.Sleep(5000);
ViewBag.name = UserName;
ViewBag.pwd = Password;
return PartialView("result");
//使用分部视图,只会返还自己写入的标签部分
}
效果图:
1.点击注册后,确认注册,短暂的Loading效果
2.最终结果