解决过程:
一、后端用list装好动态的标题数据,将原本的实体模型更改为DynamicObject,参考文章(C#基础知识---动态为类型添加属性_weixin_30596343的博客-CSDN博客),动态的添加属性,不通,发现easyui datagrid 无法识别,或者说是前端页面无法读取到数据
二、从前端方向着手
1、后端使用字典的方式动态给模型添加字段
public Dictionary
public SalesLossEstimationEntity()
{
dicProperty = new Dictionary
}
代码添加
属性:
entity.dicProperty.Add(whCode, data);
标题:
result.title.Add( whCode.ToUpper());
后端利用反射属性读取,导出:
读取:
foreach( var item in data.title)
{
names.Add("dicProperty." + item, item);
}
导出:
var properties = obj.GetType().GetProperties();
int cellIndex = 0;
foreach (var item in this.ColumnNameList)
{
//取子
if (item.Key.IndexOf('.') != -1)
{
object value = null;
string propertyName = item.Key.Split('.')[0];
string key = item.Key.Split('.')[1];
var fieldInfo = obj.GetType().GetProperty(propertyName);
var dict = fieldInfo.GetValue(obj) as Dictionary
if (dict!= null)
{
value = dict[key];
}
if (value != null)
{
InsertCellValue(value, newRow, cellIndex, true);
}
}
else
{
var ps = properties.FirstOrDefault(p => p.Name == item.Key);
if (ps != null)
{
InsertCellValue(ps.GetValue(obj, null), newRow, cellIndex, true);
}
}
cellIndex++;
}
3、前端循环读取利用子属性的方式添加标题,不通,发现asyui datagrid columns的field不支持属性的子属性,伤心欲绝,后发现可以通过修改js源文件支持,参考文章(easyui datagrid columns的field支持属性的子属性(field.field1形式或者格式化程序形式)_伊万洛夫拉裤兜的博客-CSDN博客)通过在jquery.datagrid.js文件中 搜索到renderRow函数,修改代码如下
if (col) {
/* var _1df = rowData[field];//原始内容*/
//替换内容
//field支持属性的子属性(field.field1形式或者格式化程序形式)
var _1df = undefined;
if (field !=undefined && field !=NULL && field !="" && field.indexOf('.') != -1) {
_1df = eval("rowData['" + field.replace(/\./g, "']['") + "']");
} else {
_1df = rowData[field];
}
4、前端成功读取
var checked = $("#cbGroupbyCategory").attr("checked");
//if (!checked) {
// var pagination = $('#divItemSalesLossList').datagrid('getPager').data("pagination").options;
// // 获取当前分页索引值
// param.page = pagination.pageNumber;
// // 获取当前分页条数
// param.pagesize = pagination.pageSize;
//}
var params = GetParam();
params.page = 1;
params.pagesize = 1;
CallActionForComplex("/ItemAnalyse/SalesLossEstimationList", { parameter: params }, function (result) {
if (result) {
var Columns = $.extend(true, [], baseColumns);
/*alert(result.rows[0].dicProperty["GD"]);*/
$.each(result.title, function (i, val) {
var ob = { field: "HD", title: "HD", width: 60, align: "right", formatter: GetCellContent };
ob.field = "dicProperty." + val;
ob.title = val;
Columns[0].push(ob)
});
var T = { field: "Total", title: "Total", width: 80, align: "right" };
Columns[0].push(T)
var frozenColumns = checked ? categoryColumns : ItemColumns;
$("#divItemSalesLossList").datagrid({
height: maxHeight - 90,
/*url: "/ItemAnalyse/SalesLossEstimationList",*/
queryParams: param,
pagination: !checked,
rownumbers: true,
autoLoad: false,
nowrap: false,
showFooter: true,
frozenColumns: frozenColumns,
//page: param.page,
//pagesize: param.pagesize,
columns: Columns,
/*data: { rows: result.rows, footer: result.footer, total: result.total },*/
});
$("#divItemSalesLossList").datagrid("loadData", { rows: [], total: 0 });
$("#divItemSalesLossList").datagrid("load", param);
//if (!checked) {
// $('#divItemSalesLossList').datagrid('getPager').pagination({
// onSelectPage: function (pageNumber, pageSize) {
// param.page = pageNumber;
// // 获取当前分页条数
// param.pagesize = pageSize;
// //$('#divItemSalesLossList').datagrid('getPager').pagination({
// // page: param.page,
// // pageSize: param.pagesize
// //});
// /*if (pageNumber==1)*/
// $("#divItemSalesLossList").datagrid("load", param);
// },
// });
//}
}
});
}
遇到的问题:
把原来的标题数组拿来赋值使用时,发现会影响到原有的数据,了解到javascript对象的引用赋值以及浅拷贝与深拷贝,参考文章(javascript对象的引用赋值以及浅拷贝与深拷贝_丑小鸭变黑天鹅的博客-CSDN博客_js 对象引用地址)遂使用了$.extend(true, [], baseColumns)的方式进行赋值
三、经同事提醒,发现后端可以弃掉原有的模型使用ExpandoObject
1、后端
dynamic entity= new ExpandoObject();
IDictionary
dnmObj[whCode.ToUpper()] = data;
2、前端
CallActionForComplex("/ItemAnalyse/SalesLossEstimationList", { parameter: params }, function (result) {
if (result) {
var Columns = [];
/* var Columns = $.extend(true, [], baseColumns);*/
/*alert(result.rows[0].dicProperty["GD"]);*/
$.each(result.title, function (i, val) {
var ob = { field: "HD", title: "HD", width: 60, align: "right", formatter: GetCellContent };
/* ob.field = "dicProperty." + val;*/
ob.field = val;
ob.title = val;
Columns.push(ob)
});
var T = { field: "Total", title: "Total", width: 80, align: "right" };
Columns.push(T)
var frozenColumns = checked ? categoryColumns : ItemColumns;
$("#divItemSalesLossList").datagrid({
height: maxHeight - 90,
/*url: "/ItemAnalyse/SalesLossEstimationList",*/
queryParams: param,
pagination: !checked,
rownumbers: true,
autoLoad: false,
nowrap: false,
showFooter: true,
frozenColumns: frozenColumns,
//page: param.page,
//pagesize: param.pagesize,
columns: [Columns],
/*data: { rows: result.rows, footer: result.footer, total: result.total },*/
});
$("#divItemSalesLossList").datagrid("loadData", { rows: [], total: 0 });
$("#divItemSalesLossList").datagrid("load", param);
//if (!checked) {
// $('#divItemSalesLossList').datagrid('getPager').pagination({
// onSelectPage: function (pageNumber, pageSize) {
// param.page = pageNumber;
// // 获取当前分页条数
// param.pagesize = pageSize;
// //$('#divItemSalesLossList').datagrid('getPager').pagination({
// // page: param.page,
// // pageSize: param.pagesize
// //});
// /*if (pageNumber==1)*/
// $("#divItemSalesLossList").datagrid("load", param);
// },
// });
//}
}
});
四、今天发现第一条是可以实现的,只是返回的数据要额外处理
1、模型处理
public class JsonObject : DynamicObject, IEnumerable
{
private readonly IDictionary
public JsonObject(IDictionary
{
if (dictionary == null)
{
mDictionary = new Dictionary
}
else
{
mDictionary = dictionary;
}
}
public JsonObject(object @object)
: this()
{
if (@object != null)
{
if (@object is JsonObject)
{
this.mDictionary = ((JsonObject)@object).mDictionary;
}
else
{
var props = @object.Properties().Where(a => a.GetIndexParameters().Length == 0 && a.CanRead);
foreach (PropertyInfo v in props)
{
mDictionary[v.Name] = v.GetValue(@object);
}
}
}
}
public JsonObject AddProperty(string name, object value)
{
mDictionary[name] = value;
return this;
}
public JsonObject RemoveProperty(string name)
{
mDictionary.Remove(name);
return this;
}
//合并多个对象的属性(浅表)
public JsonObject ExtendFrom(params object[] source)
{
var dic = mDictionary;
foreach (var v in source ?? new object[0])
{
var p = new JsonObject(v);
foreach (var vv in p.mDictionary)
{
if (dic.ContainsKey(vv.Key) && vv.Value == null)
continue;
dic[vv.Key] = vv.Value;
}
}
return new JsonObject(dic);
}
public IDictionary
{
get { return new ReadOnlyDictionary
}
public override string ToString()
{
var sb = new StringBuilder();
ToString(ref sb);
return sb.ToString();
}
private void ToString(ref StringBuilder sb)
{
sb.Append("{");
var needComma = false;
foreach (var pair in mDictionary)
{
if (needComma)
{
sb.Append(",");
}
needComma = true;
var value = pair.Value;
var name = pair.Key;
if (value == null)
{
sb.AppendFormat("\"{0}\":\"{1}\"", name, "");
}
else
{
sb.AppendFormat("\"{0}\":", name);
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new JsonObjectConverter() });
serializer.Serialize(value, sb);
}
}
sb.Append("}");
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (!mDictionary.TryGetValue(binder.Name, out result))
{
result = null;
return true;
}
var dictionary = result as IDictionary
if (dictionary != null)
{
result = new JsonObject(dictionary);
return true;
}
var arrayList = result as ArrayList;
if (arrayList != null && arrayList.Count > 0)
{
if (arrayList[0] is IDictionary
result = new List
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
mDictionary[binder.Name] = value;
return true;
}
public object GetValue(string name)
{
return mDictionary.ContainsKey(name) ? mDictionary[name] : null;
}
public TType GetValue
{
return GetValue(name).ConvertTo
}
public void SetValue(string name, object value)
{
mDictionary[name] = value;
}
#region interface
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
}
public IEnumerator GetEnumerator()
{
foreach (var kv in mDictionary)
{
yield return kv;
}
}
#endregion
}
2、添加属性
List
while (reader.Read())
{
t_itemId = DataHelper.ReadInt(reader, "ItemId");
if (t_itemId != itemId)
{
entity = new JsonObject();
entity.SetValue("ItemId", DataHelper.ReadInt(reader, "ItemId"));
entity.SetValue("ItemCode", DataHelper.ReadString(reader, "ItemCode"));
entity.SetValue("ItemLevel", DataHelper.ReadString(reader, "ItemLevel"));
entity.SetValue("MaxAge", DataHelper.ReadInt(reader, "MaxAge"));
entity.SetValue("AvgAge", DataHelper.ReadDecimal(reader, "AvgAge"));
entity.SetValue("ReceivingDays", DataHelper.ReadInt(reader, "ReceivingDays"));
entity.SetValue("PMName", reader.GetValueOrDefault
entity.SetValue("ItemGroup", DataHelper.ReadInt(reader, "ItemGroup"));
entity.SetValue("ItemGroupDesc", DataHelper.ReadString(reader, "ItemGroupDesc"));
list.Add(entity);
itemId = t_itemId;
}
ReadWareHouseData(reader, entity);
}
result.rows = list;
3、返回数据处理
public sealed class JsonObjectConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary
{
return new JavaScriptSerializer().ConvertToType(dictionary, type);
}
public override IDictionary
{
var result = new Dictionary
var dynamicJsonObject = obj as JsonObject;
foreach (var item in dynamicJsonObject.Dictionary)
{
result.Add(item.Key, item.Value);
}
return result;
}
public override IEnumerable
{
get { return new Type[] { typeof(JsonObject) }; }
}
public static string Serialize(object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new JsonObjectConverter() });
serializer.MaxJsonLength = Int32.MaxValue;
var rv = serializer.Serialize(obj);
rv = Regex.Replace(rv, @"\\/Date\((\-?\d+)\)\\/", match =>
{
DateTime dt = new DateTime(1970, 1, 1, 8, 0, 0);
dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
return dt.ToString("MM/dd/yyyy HH:mm:ss");
});
return rv;
}
}
return Content(JsonObjectConverter.Serialize(result), "application/json");
4、前端显示
$.getJSON("/ItemAnalyse/ItemWarningListWH").done(function (d) {
var columns = d.map(function (a) {
return { field: a.Key, title: a.Key, width: 60, align: "center", formatter: GetCellContent, styler: GetCellStyler, headStyler: _.partial(GetHeadStyle, _, _, a) };
});
$("#divItemWarningList").datagrid({
height: maxHeight - 110,
url: "/ItemAnalyse/ItemWarningList",
pagination: true,
rownumbers: true,
autoLoad: false,
nowrap: false,
frozenColumns: [[
{ field: "ItemId", title: "ItemId", width: 100, align: "left", hidden: true },
{ field: "ItemCode", title: "ItemCode", width: 100, align: "left", sortable: true },
{ field: "PMName", title: "PM", width: 120, align: "left", sortable: true },
{ field: "AvgAge", title: "AvgAge", width: 50, align: "right", sortable: true, formatter: function (val) { return val && val.toFixed(2); } },
{ field: "MaxAge", title: "MaxAge", width: 50, align: "right", sortable: true },
{ field: "ItemLevel", title: "Level", width: 50, align: "center", sortable: true },
{ field: 'ItemGroupDesc', title: 'ItemGroup', width: 70, sortable: true },
{ field: "TotalOH", title: "Total", width: 50, align: "right", sortable: true }
]],
columns: [columns],
onDblClickRow: function (rowIndex, rowData) {
viewItem(rowData.ItemId);
}
});
});
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)