当前位置 : 主页 > 网络编程 > ASP >

ASP.Net MVC 引用动态 js 脚本

来源:互联网 收集:自由互联 发布时间:2021-06-24
希望可以动态生成 js 发送给客户端使用。 layout页引用: script type="text/javascript" src="@Url.Action("Js","CommonConfig",new {version= OP.WebUI.Areas.Sys.Controllers.CommonConfigController.GetVersion()})"/script 如果使

希望可以动态生成 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","CommonConfig",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":"重派类型","IsDelete":false,"Remark":"1","Id":2,"CreateUserName":"朱皖苏","CreateTime":"2019-09-18T15:36:14.74","UpdateUserName":"朱皖苏","UpdateTime":"2019-09-18T15:36:14.74"},{"Name":"测试","Value":"2","Target":"清关地址","IsDelete":false,"Remark":"2","Id":3,"CreateUserName":"朱皖苏","CreateTime":"2019-09-18T15:40:50.687","UpdateUserName":"朱皖苏","UpdateTime":"2019-09-18T15:40:50.687"},{"Name":"测试","Value":"2","Target":"退回地址","IsDelete":false,"Remark":"4","Id":4,"CreateUserName":"朱皖苏","CreateTime":"2019-09-18T15:43:42.077","UpdateUserName":"朱皖苏","UpdateTime":"2019-09-18T15:43:42.077"},{"Name":"2","Value":"2","Target":"头程航班启运地","IsDelete":false,"Remark":"","Id":5,"CreateUserName":"朱皖苏","CreateTime":"2019-09-18T15:48:54.93","UpdateUserName":"朱皖苏","UpdateTime":"2019-09-18T15:48:54.93"},{"Name":"zws","Value":"2","Target":"重派类型","IsDelete":false,"Remark":"2","Id":6,"CreateUserName":"朱皖苏","CreateTime":"2019-09-18T15:50:05.177","UpdateUserName":"朱皖苏","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();

效果:

网友评论