bootstrap-data-target触发模态弹出窗元素的data使用 data-toggle与data-target的作用 深入ASP.NET MVC之九:Ajax支持 Asp.Net MVC4系列--进阶篇之AJAX
bootstrap-data-target触发模态弹出窗元素的data使用
标签:bootstrap-data-target触发模态弹出窗元素的data使用
1.运行效果如图所示
2.实现代码如下
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>data-target触发模态弹出窗元素</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- 可选的 Bootstrap 主题文件(一般不用引入) --> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> </head> <body> <!-- data-target触发模态弹出窗元素 --> <button class="btn btn-primary" data-toggle="modal" data-target="#mymodal-data" type="button">通过data-target触发</button> <!-- 模态弹出窗内容 --> <div class="modal fade" id="mymodal-data" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">×</span><span class="sr-only"> Close</span></button> <h4 class="modal-title">模态弹出窗标题</h4> </div> <div class="modal-body"> <p>模态弹出窗主体内容</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal"> 关闭</button> <button type="button" class="btn btn-primary">保存</button> </div> </div> </div> </div> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </body> </html>
3.说明
本文出自 “素颜” 博客,请务必保留此出处http://suyanzhu.blog.51cto.com/8050189/1930093
bootstrap-data-target触发模态弹出窗元素的data使用
标签:bootstrap-data-target触发模态弹出窗元素的data使用
原文地址:http://suyanzhu.blog.51cto.com/8050189/1930093
data-toggle与data-target的作用
<a href="login.html" data-toggle="modal" data-target="#signin-signup-tab" id="signin-button" class="pull-right">Sign In</a>
:因为Bootstrap为这些元素都绑定上了事件,而终止了链接默认行为,你可以看看Bootstrap的文档,data-toggle指以什么事件触发,常用的如modal,popover,tooltips等,data-target指事件的目标,你这段代码的意思就是指将#signin-signup-tab这个Dom元素的内容以模态框的形式展示。
深入ASP.NET MVC之九:Ajax支持
目前前端页面和服务端进行Ajax交互大多采用的都是jQuery, ASP.NET MVC提供了一些方法使得这个过程变得更加容易。常见的Ajax应用场景有两种,一个是点击一个链接,然后局部加载一些内容,可以是html片段,也可能是json数据,然后通过前端js处理之后显示;另一个是异步提交表单。这些帮助方法都是位于AjaxExtensions种的扩展方法。先看第一类场景,这是通过ActionLink来生成一个点击之后可以异步加载数据的链接。
1. Ajax Action Link
先看下如何使用这些方法,首先保证页面加载了依赖的js库:
<script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
假如有如下的Controller:
public class AjaxController : Controller
{
public ActionResult Index()
{
return View();
}
public string Result(string name)
{
System.Threading.Thread.Sleep(2000);
return "This is " + name;
}
}
View文件如下:
@{
ViewBag.Title = "Index";
string[] data = new string[] { "Jack", "Tom", "Kathy" };
}
<style type="text/css">
a {
margin:10px;
}
#loading {
display:none;
color:red;
}
</style>
<div>
@foreach (var n in data)
{
@Ajax.ActionLink(n, "Result", new { name = n }, new AjaxOptions{
UpdateTargetId = "tabledata",
LoadingElementId = "loading"
});
}
</div>
<div id="loading">
Loading Data...
</div>
<div id="tabledata">
</div>
这样的效果便是点击超链接,从Result这个action方法就会被插入到id为tabledata的div中,在加载的过程中,id为loading的div会显示。应该说,这是一种非常常见的操作场景。在asp.net mvc的帮助下,我们不需要多写任何js代码就可以实现这一效果。下面来看下这是如何实现的。先看ActionLink生成了什么html代码:
<a data-ajax="true" data-ajax-loading="#loading" data-ajax-mode="replace" data-ajax-update="#tabledata" href="/Ajax/Result?name=Jack">Jack</a>
ActionLink的源代码没有太多复杂的地方,只是按规则生成这个标签而已,唯一复杂的地方是href的生成,但这个不是本文讨论的重点,这和routing模块关系更加紧密一些,有机会另文分析。真正实现功能的地方都是在jquery.unobtrusive-ajax.js这个文件中,这是一个jquery的插件,首先在插件被加载的时候,执行了如下代码:
$("a[data-ajax=true]").live("click", function (evt) {
evt.preventDefault();
asyncRequest(this, {
url: this.href,
type: "GET",
data: []
});
});
利用jQuery的live方法设置了click事件设置为asyncRequest方法:
function asyncRequest(element, options) {
var confirm, loading, method, duration;
confirm = element.getAttribute("data-ajax-confirm");
if (confirm && !window.confirm(confirm)) {
return;
}
loading = $(element.getAttribute("data-ajax-loading"));
duration = element.getAttribute("data-ajax-loading-duration") || 0;
$.extend(options, {
type: element.getAttribute("data-ajax-method") || undefined,
url: element.getAttribute("data-ajax-url") || undefined,
beforeSend: function (xhr) {
var result;
asyncOnBeforeSend(xhr, method);
result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(this, arguments);
if (result !== false) {
loading.show(duration);
}
return result;
},
complete: function () {
loading.hide(duration);
getFunction(element.getAttribute("data-ajax-complete"), ["xhr", "status"]).apply(this, arguments);
},
success: function (data, status, xhr) {
asyncOnSuccess(element, data, xhr.getResponseHeader("Content-Type") || "text/html");
getFunction(element.getAttribute("data-ajax-success"), ["data", "status", "xhr"]).apply(this, arguments);
},
error: getFunction(element.getAttribute("data-ajax-failure"), ["xhr", "status", "error"])
});
options.data.push({ name: "X-Requested-With", value: "XMLHttpRequest" });
method = options.type.toUpperCase();
if (!isMethodProxySafe(method)) {
options.type = "POST";
options.data.push({ name: "X-HTTP-Method-Override", value: method });
}
$.ajax(options);
}
这个方法还是比较清晰的。首先根据options确定是否弹出一个确认框,然后是设置加载等待的元素和显示时间。接下来就是给options添加几个回调函数,这个options其实最终就是给jquery的ajax方法的参数。下面简单看下在设置回调函数的时候主要调用的getFunction方法:
function getFunction(code, argNames) {
var fn = window, parts = (code || "").split(".");
while (fn && parts.length) {
fn = fn[parts.shift()];
}
if (typeof (fn) === "function") {
return fn;
}
argNames.push(code);
return Function.constructor.apply(null, argNames);
}
这个方法接受两个参数,第一个code,就是在AjaxOptions中OnXXX属性上设置的值,第二个是argNames,表示的是这个回调函数的参数名字。首先它是从window对象开始查找是否有名字为code的函数,如果有,就直接返回那个函数;否则,code就是代码而不是函数名称,利用Function的构造函数创建一个新的函数。因此,OnBegin的值用如下的两种形式都是可以的:
@Ajax.ActionLink(n, "Result", new { name = n }, new AjaxOptions{
UpdateTargetId = "tabledata",
LoadingElementId = "loading",OnBegin=" alert(\"on begin\");return false;"
});
或者
<script type="text/javascript">
function Begin() {
alert("on begin");
}
</script>
@Ajax.ActionLink(n, "Result", new { name = n }, new AjaxOptions
{
UpdateTargetId = "tabledata",
LoadingElementId = "loading",
OnBegin = " Begin"
});
用第一种方式仍然可以使用参数。参数的名字见源代码。这里的JavaScript技巧值得学习下。ActionLink的原理就是这样,把原来使用jquery要做的一些准备工作包装的更加简单。
等到调用结束之后,在OnSuccess的时候,会默认执行如下方法:
function asyncOnSuccess(element, data, contentType) {
var mode;
if (contentType.indexOf("application/x-javascript") !== -1) { // jQuery already executes JavaScript for us
return;
}
mode = (element.getAttribute("data-ajax-mode") || "").toUpperCase();
$(element.getAttribute("data-ajax-update")).each(function (i, update) {
var top;
switch (mode) {
case "BEFORE":
top = update.firstChild;
$("<div />").html(data).contents().each(function () {
update.insertBefore(this, top);
});
break;
case "AFTER":
$("<div />").html(data).contents().each(function () {
update.appendChild(this);
});
break;
default:
$(update).html(data);
break;
}
});
}
注意这里,UpdateTargetId如果不填或者没有找到元素,那么就不会发生任何事。这种情况适合服务器端返回的是json,xml等类型的数据而不是html,当我们拿到数据之后,需要通过JavaScript来生成要显示的html。
2. Ajax Form
Ajax Form的原理和ActionLink很像,唯一不同的是提交表单到一个地址,然后得到获得的数据:
@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" , Url=Url.Action("Result")}))
{
@Html.EditorFor(m => m)
<input type="submit" value="submit" />
}
<div id="result">
</div>
Action代码如下:
public string Result(Course course)
{
System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();
return s.Serialize(course);
}
本章将开始介绍MVC中Ajax的使用
以一个非Ajax版本开始
Controller
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
public class PeopleController : Controller { private readonly Person[] _personData = {new Person {FirstName = "Iori",LastName = "Lan", Role = Role.Admin},new Person {FirstName = "Edwin", LastName= "Sanderson", Role = Role.Admin},new Person {FirstName = "John",LastName = "Griffyth", Role = Role.User},new Person {FirstName = "Tik",LastName = "Smith", Role = Role.User},new Person {FirstName = "Anne",LastName = "Jones", Role = Role.Guest}}; public ActionResult Index() { return View("List"); } public ActionResult GetPeople() { return View("List",_personData); } [HttpPost] public ActionResult GetPeople(string selectedRole) { if (selectedRole == null || selectedRole == "All") { returnView("List",_personData); } var selected = (Role)Enum.Parse(typeof(Role), selectedRole); return View("List",_personData.Where(p => p.Role ==selected)); }} |
Model
|
1
2
3
4
5
6
7
8
9
10
11
12
|
public class Person { public string FirstName { get; set; } public string LastName { get; set; } public Role Role { get; set; } } public enum Role { Admin, User, Guest } |
View
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
@{ Layout = null;} @using MVCAjax.Models@model IEnumerable<person>@{ViewBag.Title = "GetPeZ喎�"/kf/ware/vc/" target="_blank" class="keylink">vcGxl";}<h2>Get People</h2>@foreach (var p in Model) {}<table><thead><tr><th>First</th><th>Last</th><th>Role</th></tr></thead><tbody><tr><td>@p.FirstName</td><td>@p.LastName</td><td>@p.Role</td></tr></tbody></table>@using (Html.BeginForm()) {<p>@Html.DropDownList("selectedRole",new SelectList(new []{"All"}.Concat(Enum.GetNames(typeof(Role)))))<button type="submit">Submit</button></p>}</person> |
测试:

验证请求类型
在IE中打开F12->Network ,我们可以看到请求的发起者是click操作,因为不是xmlHttpRequest,因而不是ajax请求

使用Ajax重构代码
配置Unobstrusiveajax
打开web.config
确保这一行在appconfig节点中:
|
1
|
JavaScriptEnabled" value="true" /></add> |
打开App_Start/BundleConfig.cs,确保已添加(默认已添加):
|
1
2
3
4
5
6
7
8
9
|
bundles.Add(newScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include( "~/Scripts/jquery-ui-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.unobtrusive*", "~/Scripts/jquery.validate*")); |
原因:我们需要的是jquery.1.7.1.js 和jquery.unobstrucsive-ajax.min.js,这两个包已经包含了,在layout中render就可以了。
打开_layout.cshtml
在中render 这两个包:
|
1
2
|
@Scripts.Render("~/bundles/jquery")@Scripts.Render("~/bundles/jqueryval") |
注意:在View确保没有把@{layout=null},否则layout没有应用导致没有renderbundle,以致于无法render需要的script。
Controller 添加Action:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public ActionResult AjaxGetPeople() { return View("AjaxList"); } public PartialViewResult GetPeoplePartial(string selectedRole = "All") { IEnumerable<person> data = _personData; if(selectedRole != "All") { var selected = (Role)Enum.Parse(typeof(Role), selectedRole); data =_personData.Where(p => p.Role == selected); } return PartialView("PeoplePartialList",data); }</person> |
添加PartialViewPeoplePartialList.cshtml :
|
1
2
3
4
5
6
7
8
9
|
@using MVCAjax.Models@model IEnumerable<person>@foreach (Person p in Model) {@p.FirstName@p.LastName@p.Role}</person> |
添加View: AjaxList.cshtml :
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
@using MVCAjax.Models@model string@{ViewBag.Title = "GetPeople";var ajaxOpts = new AjaxOptions {UpdateTargetId = "tableBody"};}<h2>Get People</h2>@Html.Action("GetPeoplePartial", new {selectedRole= Model })<table><thead><tr><th>First</th><th>Last</th><th>Role</th></tr></thead><tbody id="tableBody"></tbody></table>@using(Ajax.BeginForm("GetPeoplePartial",ajaxOpts)) {<p>@Html.DropDownList("selectedRole", new SelectList(new []{"All"}.Concat(Enum.GetNames(typeof(Role)))))<button type="submit">Submit</button></p>} |
运行:

F12->Network 查看请求

可以看到,initiator 为XMLHttpRequest ,验证了请求确实是Ajax。
分析Obstrusivejavascript 工作原理
|
1
|
<form action="/People/GetPeoplePartial" data-ajax="true" data-ajax-mode="replace" data-ajax-update="#tableBody" id="form0" method="post"></form> |
这是MVC Framework生成的form tag,对于unobsrutive javascript 来说,他关心的是data-ajax=”true”和data-ajax开头的attribute,首先找到所有data-ajax=”true”的form,然后根据data-ajax-mode找到data-ajax-update的id(注意,unobstrusivejs 基于Jquery,需要加#)完成局部刷新。
Ajax Options
以下列出一些常用的AjaxOptions :
|
Confirm |
发起请求前弹出确认框,指定确认框的文字 |
|
HttpMethod |
请求类型:POST,GET,PUT,DELETE等等 |
|
InsertionMode |
Replace,Before,After, 默认为Replace |
|
LoadingElementId |
请求发出后,收到Server回应前弹出一个loading的p,这里指定p id |
|
LoadingElementDuration |
设置loading Div最多显示多少秒 |
|
UpdateTargetId |
要局部更新的container id |
|
Url |
发请求的url |
Loading 和Confirmation
现在稍作改动,给例子加一个Confirmation和loading
准备loading的p和css
Css:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<style type="text/css"> .popup_background { z-index: 10; position: fixed; top: 0; bottom: 0; left: 0; right: 0; opacity: 0.4; } .popup_loading { z-index: 11; font-size: 50px; top: 400px; left: 600px; position: absolute; }</style> |
仅作为演示,我hard-code了loading p的位置,实际项目中需要调整
Html:
|
1
2
3
4
5
|
<p id="loading" class="popup_background" style="display:none"> </p><p class="popup_loading"> </p><p>Loading...</p> <p></p><p></p> |
在AjaxOption中指定Id
|
1
2
3
4
5
6
|
var ajaxOpts = new AjaxOptions {UpdateTargetId = "tableBody" ,Confirm = "Sure?",LoadingElementDuration = 2000,LoadingElementId = "loading"}; |
在Controller中模拟一个长时间的任务
Sleep 3秒
|
1
2
3
4
|
private void MockLongTimeProcessing() { Thread.Sleep(3000); } |
在partialview中调用一下
|
1
2
3
4
5
|
public PartialViewResult GetPeoplePartial(string selectedRole ="All") { MockLongTimeProcessing();...} |
运行,查看效果:

Ajax链接
Ajax链接的生成很简单。
稍作改动,看一下ajax链接的使用方法,在View(AjaxList.cshtml)中添加:
|
1
2
3
4
5
6
7
8
9
|
<p>@foreach (string role in Enum.GetNames(typeof(Role))) {</p><p class="ajaxLink">@Ajax.ActionLink(role,"GetPeoplePartial",new {selectedRole= role},ajaxOpts)</p>}<p></p> |
这样就可以了,其实就是调用Ajax.ActionLink函数,设置链接的文字,Action,以及参数,最后一个是AjaxOption,我们用的是前面一个demo的。
添加对Json的支持
改动Controller
和前面的步骤一样,添加两个Action,一个是服务第一次加载页面的 请求,我们返回View,一个是Ajax过来的,我们需要返回JsonResult:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public ActionResult JsonList() { return View("JsonList"); } public JsonResult GetPeopleJson(string selectedRole = "All") { IEnumerable<person> data = _personData; if (selectedRole !="All") { var selected =(Role)Enum.Parse(typeof(Role), selectedRole); data =_personData.Where(p => p.Role == selected); } return Json(data,JsonRequestBehavior.AllowGet); }</person> |
添加View:
JsonList.cshtml
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
@using MVCAjax.Models@model string@{ViewBag.Title = "GetPeople";var ajaxOpts = new AjaxOptions {UpdateTargetId = "tableBody", };}<script type="text/javascript"> function processData(data) { var target =$("#tableBody"); target.empty(); for (var i = 0; i <data.length; i++)="" {="" var="" person="data[i];" target.append("<tr="">" + person.FirstName +"" + person.LastName +"" + person.Role +""); } }</script><h2>Get Json List</h2> @Html.Action("GetPeoplePartial", new {selectedRole = Model })<table><thead><tr><th>First</th><th>Last</th><th>Role</th></tr></thead><tbody id="tableBody"></tbody></table> <p>@foreach (string role in Enum.GetNames(typeof(Role))) {</p><p class="ajaxLink">@Ajax.ActionLink(role, "GetPeople",new {selectedRole = role},new AjaxOptions {Url = Url.Action("GetPeopleJson", new {selectedRole = role}),OnSuccess = "processData"})</p>}<p></p></data.length;> |
为了简便演示,仅仅展示Json部分,笔者拿掉了Loading和Confirm的部分。
代码分析
代码的核心在于OnSuccess = "processData" 。
当Ajax请求成功时,指向processData函数,在这个函数里面,我们拿到id(JqueryId)为#tableBody的表单,清空,手动拼html,并用jquery添加到这个html control中。这部分可以优化,可以选择handlebar.js,knockout.js 等js template。
在table body中调用了@Html.Action("GetPeoplePartial",new {selectedRole = Model }),和前面的原因一样,为了第一次加载时显示出所有人员列表。
另外,AjaxOptions中还有其他Callback类型;
OnBegin : 发请求前
OnFailure :请求失败
OnSuccess :请求成功
OnComplete :请求完毕
https://www.2cto.com/kf/201404/293702.html




浙公网安备 33010602011771号