加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

ASP.Net MVC 引用动态 js 脚本

发布时间:2020-12-16 09:27:20 所属栏目:asp.Net 来源:网络整理
导读:希望可以动态生成 js? 发送给客户端使用。 layout页引用: script type="text/javascript" src="@Url.Action("Js","CommonConfig",new {version= OP.WebUI.Areas.Sys.Controllers.CommonConfigController.GetVersion()})"/script 如果使用了 Nginx 反向代理

希望可以动态生成 js? 发送给客户端使用。

layout页引用:

<script type="text/javascript" src="@Url.Action("Js","CommonConfig",new {version= OP.WebUI.Areas.Sys.Controllers.CommonConfigController.GetVersion()})"></script>

如果使用了 Nginx 反向代理,且代理的端口号不是80,下面的写法可能会异常

<script type="text/javascript" src="@Url.Action("Js",new {version= OP.WebUI.Areas.Sys.Controllers.CommonConfigController.GetVersion()},"http")"></script>

因为端口号可能会错误。比如它有可能映射成?域名:8080/xxx/xxx 而你的请求地址是 域名/xxx/xx。

当更新 js 内容的时候就修改 version 即可。

控制器:

我这里的例子是把数据和 一些 js 函数一并放到一起了。

    public class CommonConfigController : Core.ControllerBase
    {
        private static short version;
        private static object versionLocker = new object();
        private readonly Lazy<ICommonConfigService> commonConfigService;
        public CommonConfigController(Lazy<ICommonConfigService> commonConfigService)
        {
            this.commonConfigService = commonConfigService;
        }

        public ActionResult CommonConfig()
        {
            return View();
        }

        public ActionResult GetCommonConfigData(QueryModel queryModel)
        {
            var res = commonConfigService.Value.GetCommonConfigData(queryModel);

            return ReturnPageData(res);
        }

        public ActionResult AddConfig()
        {
            return View();
        }

        [HttpPost]
        public JsonResult DoAddConfig(Sys_CommonConfig config)
        {
            commonConfigService.Value.AddConfig(config);
            IncrVersion();
            return JsonManager.GetSuccess();
        }

        [HttpPost]
        public JsonResult DeleteConfig(string ids)
        {
            commonConfigService.Value.DeleteConfig(ids);
            IncrVersion();
            return JsonManager.GetSuccess();
        }

        public ContentResult Js(long version)
        {
            string data = $";debugger; var CC_DATA ={commonConfigService.Value.GetCommonConfigData(m => m.IsDelete == false).ToJson()};var CC_TAG = {{version:{version}}};";

            string func = @"; (function(){
            if (CC_DATA && CC_DATA.length > 0) {
                for (var i = 0; i < CC_DATA.length; i++) {
                    var item = CC_DATA[i];
                    var tag = item.Target;
                    if (!CC_TAG[tag]) CC_TAG[tag] = [];
                    CC_TAG[tag].push(item);
                }
            }})()".Replace("@version",version.ToString());

            string extend = @"
   ; !function ($) {
        
        $.fn.extend({
            ccSelect: function () {
                var $this = $(this);
                var tag = $this.attr(`cc-tag`);
                var value = $this.attr(`cc-val`);
                if (!tag) return;
                var data = CC_TAG[tag];
                if (!data || data.length === 0) return;

                let opts = [‘<option></option>‘];
                for (var i = 0,l = data.length; i < l; i++) {
                    if( value == data[i].Value || value == data[i].Name ){
                      opts.push(‘<option selected value=`‘ + data[i].Value + ‘`>‘ + data[i].Name + `</option>`)
                    }
                    else{
                     opts.push(‘<option value=`‘ + data[i].Value + ‘`>‘ + data[i].Name + `</option>`)
                    }
                }
                $this.html(opts.join(‘‘));

                 if ($this.hasClass(‘chosen-select‘)) {
                     $this.chosen({
                     no_results_text: `未找到`,allow_single_deselect: true,search_contains: true
                })
                $this.trigger(`chosen:updated`);
                return  $this ;
                }
            }
        })
    }(jQuery)";

            Response.AddHeader("Cache-Control","max-age=120"); //緩存
            Response.AddHeader("Last-Modified",DateTime.Now.ToString("U",DateTimeFormatInfo.InvariantInfo));
            return Content(data + func + extend,"application/javascript",Encoding.UTF8);
        }

        public static short GetVersion()
        {
            lock (versionLocker)
            {
                return version;
            }
        }
        public void IncrVersion()
        {
            lock (versionLocker)
                unchecked
                {
                    version++;
                }
        }
    }

生成的 js 效果:

;debugger; var CC_DATA =[{"Name":"测试","Value":"测试","Target":"头程航班启运地","IsDelete":false,"Remark":"14","Id":1,"CreateUserName":"朱皖苏","CreateTime":"2019-09-18T14:31:59","UpdateUserName":"朱皖苏","UpdateTime":"2019-09-18T14:31:59"},{"Name":"2","Value":"2","Target":"重派类型","Remark":"1","Id":2,"CreateTime":"2019-09-18T15:36:14.74","UpdateTime":"2019-09-18T15:36:14.74"},{"Name":"测试","Target":"清关地址","Remark":"2","Id":3,"CreateTime":"2019-09-18T15:40:50.687","UpdateTime":"2019-09-18T15:40:50.687"},"Target":"退回地址","Remark":"4","Id":4,"CreateTime":"2019-09-18T15:43:42.077","UpdateTime":"2019-09-18T15:43:42.077"},"Remark":"","Id":5,"CreateTime":"2019-09-18T15:48:54.93","UpdateTime":"2019-09-18T15:48:54.93"},{"Name":"zws","Id":6,"CreateTime":"2019-09-18T15:50:05.177","UpdateTime":"2019-09-18T15:50:05.177"}];var CC_TAG = {version:0};; (function(){
            if (CC_DATA && CC_DATA.length > 0) {
                for (var i = 0; i < CC_DATA.length; i++) {
                    var item = CC_DATA[i];
                    var tag = item.Target;
                    if (!CC_TAG[tag]) CC_TAG[tag] = [];
                    CC_TAG[tag].push(item);
                }
            }})()
   ; !function ($) {
        $.fn.extend({
            ccSelect: function () {
                var $this = $(this);
                var tag = $this.attr(`cc-tag`);
                var value = $this.attr(`cc-val`);
                if (!tag) return;
                var data = CC_TAG[tag];
                if (!data || data.length === 0) return;

                let opts = [‘<option></option>‘];
                for (var i = 0,l = data.length; i < l; i++) {
                    if( value == data[i].Value || value == data[i].Name ){
                      opts.push(‘<option selected value=`‘ + data[i].Value + ‘`>‘ + data[i].Name + `</option>`)
                    }
                    else{
                     opts.push(‘<option value=`‘ + data[i].Value + ‘`>‘ + data[i].Name + `</option>`)
                    }
                }
                $this.html(opts.join(‘‘));

                 if ($this.hasClass(‘chosen-select‘)) {
                     $this.chosen({
                     no_results_text: `未找到`,allow_single_deselect: true,search_contains: true
                })
                $this.trigger(`chosen:updated`);
                return  $this ;
                }
            }
        })
    }(jQuery)

可以吧一些实体的元数据信息发送到客户端,实现UI层的 Entity 结构层,

也可以把一些枚举映射发送到客户端,可以实现一些 format,

我这里是维护了一个通用配置,用来配置一些动态的下拉框UI组件,并且使用??chosen-select 插件,基于动态数据实现了一个小的 jQuery 插件。

使用方法:

<select class="cc-select chosen-select width-40" cc-tag="头程航班启运地" cc-val="default" ></select>

 $(‘.cc-select‘).ccSelect();

效果:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读