ASP.NET Core中的jQuery Unobtrusive Ajax帮助器

最近在ASP.NET Core下写文章管理系统时,准备在分页显示文章内容时,使用Ajax。网上找了篇帖文,简单翻一下,仅供自己查阅。

本贴讲述了如何在ASP.NET Core中获取jQuery Unobtrusive Ajax帮助器。AjaxHelper类为用AJAX渲染HTML视图提供支持。如果你想将现有的ASP.NET MVC项目迁移到ASP.NET Core MVC,却没有现成的标记帮助器可供替换,取而代之的是ASP.NET Core团队建议使用data-*属性。所有现存的@Ajax.Form属性都可用于data-*属性。

要使用它,你首先需要引用jqueryjquery.unobtrusive-ajax脚本,可以通过bower下载并安装它。

这是通过bower安装该脚本库的命令:

bower install Microsoft.jQuery.Unobtrusive.Ajax

一旦你安装了该脚本,你就可以在_layout.cshtml文件引用它:

<script src="~/lib/Microsoft.jQuery.Unobtrusive.Ajax/jquery.unobtrusive-ajax.min.js"></script>

以下是可用于迁移@Ajax.Form帮助器的属性:

AjaxOptionsHTML attribute
Confirmdata-ajax-confirm
HttpMethoddata-ajax-method
InsertionModedata-ajax-mode
LoadingElementDurationdata-ajax-loading-duration
LoadingElementIddata-ajax-loading
OnBegindata-ajax-begin
OnCompletedata-ajax-complete
OnFailuredata-ajax-failure
OnSuccessdata-ajax-success
UpdateTargetIddata-ajax-update
Urldata-ajax-url

你像这样在表单(Form)元素中添加这些属性:

<form asp-controller="Home" asp-action="SaveForm" data-ajax="true" data-ajax-method="POST">
</form>

下列代码,将在提交表单时显示进度指示器,一旦完成(onComplete)、成功(onSuccess)或失败(Failed),它将显示警告消息。

var results = $("#Results");
var onBegin = function(){
    results.html("<img src=\"/images/ajax-loader.gif\" alt=\"Loading\" />");
};

var onComplete = function(){
    results.html("");
};

var onSuccess = function(context){
    alert(context);
};

var onFailed = function(context){
    alert("Failed");
};

这是HTML表单:

<form asp-controller="Home" asp-action="SaveForm"
    data-ajax-begin="onBegin" data-ajax-complete="onComplete"
    data-ajax-failure="onFailed" data-ajax-success="onSuccess"
    data-ajax="true" data-ajax-method="POST">
    <input type="submit" value="Save" class="btn btn-primary" />
    <div id="Results"></div>
</form>

ASP.Net Core中使用jquery-ajax-unobtrusive替换Ajax.BeginForm

在大潮流下,大家都在研究MVVM框架,但是做面向搜索引擎的外网项目还是得用服务器渲染。

在.Net中肯定就是用Razor模板引擎了。

.Net Core断臂式重构后,很多在老得Mvc中使用得好好的一些功能,突然就不见了。

在这里鄙视一下微软,说好的无缝切换呢。。我看这个缝还是有点大。

ASP.Net Core中,使用TagHelper替换HtmlHelper。使得写出的Razor代码可读性更高,同时VS的提示能力更强了。

但是也丢掉了很多以前觉得很好用的东西,比如今天要说的Ajax.BeginForm,在ASP.Net Core中突然就不见了,搜索GitHub的Issue,发现官方不打算支持Ajax.BeginForm了。后续也无开发计划,那个issue直接被关闭了。

虽然没了Ajax.BeginForm。但是在墙外搜索到另一种TagHelper的实现。

直接在form上使用data-*去做异步表单,使用方式和Ajax.BeginForm半斤八两

https://github.com/aspnet/jquery-ajax-unobtrusive

去GitHub下载这个项目,然后点击build.cmd,脚本自动构建一个dilst,里面就是js文件

然后引用到项目中。就可以愉快的编写异步表单辣

<form asp-controller="Home" asp-action="Test" data-ajax="true" data-ajax-method="post" data-ajax-begin="begin" data-ajax-success="success">
    <label asp-for="UserName"></label>:
    <input asp-for="UserName" />
    <span asp-validation-for="UserName"></span>
    <br />
    <label asp-for="PassWord"></label>:
    <input asp-for="PassWord" />
    <span asp-validation-for="PassWord"></span>
    <button type="submit">Ok</button>
</form>
  <script>
        var begin = function () {
            console.log("begin");
        }
        var success = function (context) {
            console.log(context)

        }
    </script>

这里提供了N多个data-ajax-*taghelper

AjaxOptionsHTML attribute
Confirmdata-ajax-confirm
HttpMethoddata-ajax-method
InsertionModedata-ajax-mode
LoadingElementDurationdata-ajax-loading-duration
LoadingElementIddata-ajax-loading
OnBegindata-ajax-begin
OnCompletedata-ajax-complete
OnFailuredata-ajax-failure
OnSuccessdata-ajax-success
UpdateTargetIddata-ajax-update
Urldata-ajax-url

jquery.unobtrusive-ajax.js

Ajax Option对应

Ajax OptionHTML attributeDescribe
Confirmdata-ajax-confirm设置一个确定取消弹出框的文字,没有则不设置
HttpMethoddata-ajax-method提交方式
InsertionModedata-ajax-mode*更新的形式 BEFORE插入到对象之前 AFTER插入到对象之后 为空就是覆盖
LoadingElementDurationdata-ajax-loading-duration**持续时间 默认是0
LoadingElementIddata-ajax-loading显示loading的对象
OnBegindata-ajax-beginajax前触发的函数或者一段程序
OnCompletedata-ajax-complete完成后,此时还没有加载返回的数据,请求成功或失败时均调用
OnFailuredata-ajax-failure失败
OnSuccessdata-ajax-success成功,加载完成的数据
Urldata-ajax-update更新的对象
Urldata-ajax-url提交url
data-ajax=true开启绑定jquery.unobtrusive
  1. Ajax Option展示
@using (Ajax.BeginForm("AjaxUploadImage", "Home", new AjaxOptions
        {
            Confirm = "1111",
            HttpMethod = "POST",
            InsertionMode = InsertionMode.Replace,
            LoadingElementDuration = 1000,
            LoadingElementId = "222",
            OnBegin = "Begin",
            OnComplete = "Completed",
            OnFailure = "OnFailured",
            OnSuccess = "OnSuccessd",
            UpdateTargetId = "updata",
            Url = "",
        }, new { @id = "frm", enctype = "multipart/form-data" }))
        {
            <input id="IconUrl" name="IconUrl" />
            <input type="file" id="files" name="files" value="点击选择图片" />
        }
  1. HTML attribute展示
<form action="/Home/AjaxUploadImage?Length=4" data-ajax="true" data-ajax-begin="Begin" data-ajax-complete="Completed" data-ajax-confirm="1111" data-ajax-failure="OnFailured" data-ajax-loading="#222" data-ajax-loading-duration="1000" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-success="OnSuccessd" data-ajax-update="#updata" enctype="multipart/form-data" id="frm" method="post">
            <input id="IconUrl" name="IconUrl" />
            <input type="file" id="files" name="files" value="点击选择图片" />
</form>

jquery.unobtrusive-ajax.js单独的用法

(插件本身已经减少了人力,如果开始无脑开发,简直就是无能,@Ajax里面哪里帮助类生成的其实就是jquery.unobtrusive的一些特性)

jquery.unobtrusive是MVC中出现的jquery插件,用与和MVCAjax交互,但是我不怎么喜欢在构建页面的时候用@Ajax.XXX去构建,感觉太依赖了,jquery.unobtrusive应该是所有web后端语言都能用的东西。所以就有了自己的单独使用jquery.unobtrusive的旅程,研究jquery.unobtrusive的用法和源码(之前已经有过阅读源码的文章和一定的注释,地址:http://www.cnblogs.com/RainbowInTheSky/p/4466993.html)。

用法data-ajax="true"是开启jquery.unobtrusive

$(element.getAttribute("data-ajax-update"))

源码中有这样一段,说明data-ajax-update的值就是选择器得到的,可以直接#id,.class。(data-ajax-update//更新的对象

经常与data-ajax-mode配合使用

data-ajax-mode//更新的形式 BEFORE插入到对象之前 AFTER插入到对象之后 为空就是覆盖

函数调用

data-ajax-begin
data-ajax-complete
data-ajax-success
data-ajax-failure

上面的四个属性对应$.ajax中的beforeSend,complete,success,error,他们的参数可以是程序片段,也可以是一个function,但是在写参数的时候不能是functiong(){}这样的匿名函数。基本涵盖了ajax,满足了需求。

不过在使用

data-ajax-loading//显示loading的对象

data-ajax-loading-duration//持续时间 默认是0

这两个属性的时候需要扩展一下,因为jquery.unobtrusive没有对齐做UI的实现,需要自己扩展。data-ajax-loading就是需要显示的对象,data-ajax-loading-duration是持续时间,他们使用的是jquery.show(),和jquery.hide()这两个函数。为此我写了一个遮罩的扩展

 //创建简单遮罩层,显示load时的信息,配合Unobtrusive
 ; (function ($) {
         //设置背景层高
         function height() {
             var scrollHeight, offsetHeight;
             // handle IE 6
             if ($.browser.msie && $.browser.version < 7) {
                 scrollHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
                 offsetHeight = Math.max(document.documentElement.offsetHeight, document.body.offsetHeight);
                 if (scrollHeight < offsetHeight) {
                     return $(window).height();
                 } else {
                     return scrollHeight;
                 }
                 // handle "good" browsers
             }
             else if ($.browser.msie && $.browser.version == 8) {
                 return $(document).height() - 4;
             }
             else {
                 return $(document).height();
             }
         };
         //设置背景层宽
         function width() {
             var scrollWidth, offsetWidth;
             // handle IE
             if ($.browser.msie) {
                 scrollWidth = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth);
                 offsetWidth = Math.max(document.documentElement.offsetWidth, document.body.offsetWidth);
                 if (scrollWidth < offsetWidth) {
                     return $(window).width();
                 } else {
                     return scrollWidth;
                 }
                 // handle "good" browsers
             }
             else {
                 return $(document).width();
             }
         };
         /*==========全部遮罩=========*/
         function createLayer(load) {
             //背景遮罩层
             var layer = $("<div id=" + load.attr("data-loadlayer-id") + "></div>");
             layer.css({
                 zIndex: 9998,
                 position: "absolute",
                 height: height() + "px",
                 width: width() + "px",
                 background: "black",
                 top: 0,
                 left: 0,
                 filter: "alpha(opacity=30)",
                 opacity: 0.3
             });
 
             //图片及文字层
             var content = $("<div id=" + load.attr("data-loadlayer-id") + "-content" + "></div>");
             content.css({
                 textAlign: "left",
                 position: "absolute",
                 zIndex: 9999,
                 //height: opt.height + "px",
                 //width: opt.width + "px",
                 top: "50%",
                 left: "50%",
                 verticalAlign: "middle",
                 //background: opt.backgroudColor,"#ECECEC"
                 background: "#ECECEC",
                 borderRadius: "3px",
                 padding:"2px 5px 2px 5px",
                 fontSize: "13px"
             });
 
             //content.append("<img style='vertical-align:middle;margin:" + (opt.height / 4) + "px; 0 0 5px;margin-right:5px;' src='" + opt.backgroundImage + "' /><span style='text-align:center; vertical-align:middle;'>" + opt.text + "</span>");
             content.append("<span style='text-align:center; vertical-align:middle;color:#000000'>" + load.attr("data-loadlayer-msg") + "</span>");
             load.append(layer.append(content));
             var top = content.css("top").replace('px', '');
             var left = content.css("left").replace('px', '');
             content.css("top", (parseFloat(top) - parseFloat(content.css("height")) / 2)).css("left", (parseFloat(left) - parseFloat(content.css("width")) / 2));
 
             layer.hide();
             return this;
         }
 
         $(document).ready(function () {
             createLayer($("div[data-loadlayer=true]"))
         });
 })(jQuery)

使用方法

<div data-loadlayer="true" data-loadlayer-id="load" data-loadlayer-msg="loading..."></div>

然后需要在调用的地方data-ajax-loading="#load"即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值