前一段时间比较忙,没来得急写新的东西,哈哈,这次我就写一写上次在项目中在后台生成js文件,以供前端数据的格式化使用
使用目的: 同一个项目组的小伙伴把订单状态都用字典项维护了起来,这样的好处我就不多说了,但是前台页面有展示的时候就要格式化。所以就需要将字典项的值读出来生成js文件,前台来调用并格式化字段,达到展示订单状态的目的。
好了,废话不多说,现在开始上代码了
public async Task<ActionResult> XXX() { var dicList = await _DictionarysRepository.GetAllListAsync();//读取字典项List var listDto = dicList.MapTo<List<DictionarysListDto>>(); StringBuilder sb = new StringBuilder(); sb.Append("(function ($) {"); foreach (var item in listDto) { sb.Append(string.Format("abp.{0}={1};", item.Code, item.DictionaryItem.ToJsonString())); string tempStr = "abp." + item.Code + "Format=function (){ var retStr = $(abp." + item.Code + ").filter(function (state) { return this.ItemCode === state; })[0].ItemName; return retStr;};"; sb.Append(tempStr); } sb.Append("})(jQuery);"); return Content(sb.ToString(), "application/x-javascript", Encoding.UTF8); }说明:
1、item.Code 就是编号, item.DictionaryItem.ToJsonString() 就是字典项的名称
2、abp." + item.Code + "Format 这一句就是调用的方法名, $(abp." + item.Code + ") 就是调用上一句代码 ,根据传进来的参数,进行遍历,返回对应的itemName
前台调用:<script src="~/Script/GetMemeberDictionaryScript?v=@(Clock.Now.Ticks)" type="text/javascript"></script>
调用方法:
abp.ProblemTypeFormat( data.record.problemType);
通过这样,就可以将订单状态格式化成对应的说明,且随着字典项的修改而不用作出任何变更。生成的js文件代码:
(function($) { abp.ProblemType = [{ "Id": 7, "ItemCode": "1", "ItemName": "损坏" }, { "Id": 8, "ItemCode": "2", "ItemName": "丢失" }, { "Id": 9, "ItemCode": "3", "ItemName": "禁运" }]; abp.ProblemTypeFormat = function() { var retStr = $(abp.ProblemType).filter(function(state) { return this.ItemCode === state; })[0].ItemName; return retStr; }; })(jQuery); 是不是很方便呢?