[英]RuntimeBinderException with dynamic anonymous objects in MVC
[英]MVC 5 Build a dynamic anonymous object
我正在研究MVC 5應用程序,並嘗試允許用戶編寫自己的查詢並在Jquery DataTables中顯示結果。 我很難確定如何根據用戶輸入動態構建匿名JSON對象。
理論上,用戶將發送列列表和where子句以構建SQL查詢。 我會像這樣運行SQL查詢,並構建我的對象。
如何根據用戶輸入的內容動態構建“select new {DT_RowId = a.id,name = a.name,number = a.number}”。
var v = (from a in dc.Products.SqlQuery(querystring) select new { DT_RowId = a.id, name = a.name, number = a.number }).ToList();
最終JSON響應是
data“:[{”id“:56,”name“:”Product 55“,”number“:”55“}]
它在硬編碼時工作正常。 否則,我將不得不從產品中選擇*,然后在客戶端顯示/隱藏列,這樣如果所有列都從服務器返回,則會使我的數據有效載荷非常大。
有沒有辦法循環遍歷請求的屬性來構建這個匿名對象? 我試圖使用一個字典但是Json返回的是非常不同的,它有Key和Value,而這並不是DataTables所期望的。
謝謝!
完整的控制器代碼
using (DataTableExampleContext dc = new DataTableExampleContext())
{
var v = (from a in dc.Products.SqlQuery(querystring) select new { DT_RowId = a.id, name = a.name, number = a.number }).ToList();
recordsTotal = v.Count();
var data = v.Skip(skip).Take(pageSize).ToList();
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }, JsonRequestBehavior.AllowGet);
}
解決方案感謝Phillipe
using (DataTableExampleContext dc = new DataTableExampleContext())
{
var v = (from a in dc.Products.SqlQuery(querystring) select GetResult(a, ColumnNames)).ToList();
recordsTotal = v.Count();
var data = v.Skip(skip).Take(pageSize).ToList();
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }, JsonRequestBehavior.AllowGet);
}
}
public Dictionary<string,object> GetResult(Product p, List<string> columnNames)
{
var properties = TypeDescriptor.GetProperties(typeof(Product));
var dict = new Dictionary<string, object>();
foreach (var x in columnNames)
{
if (x == "id")
{
dict["DT_RowId"] = properties[x].GetValue(p);
}
else
{
dict[x] = properties[x].GetValue(p);
}
}
return dict;
}
如果您正在使用JSON.NET,則字典應序列化,並將Key的值作為屬性名稱,並將與鍵關聯的值作為屬性值進行序列化。
如果您正在使用DataContractJsonSerializer,則需要將UseSimpleDictionaryFormat
設置為true。
然后,您將使用屬性的名稱作為鍵來構建字典,並將值作為值。 如果用戶選擇他們想要的名稱,你會做類似outputDict.Add(nameof(x.Name), x.Name);
然后返回序列化庫序列化的字典。
1 /要從名稱中獲取屬性的值,可以使用屬性描述符:
var properties = TypeDescriptor.GetProperties(typeof(Product));
var value = properties[name].GetValue(product);
2 /要構建答案,您可以創建一個dynamic
對象:
dynamic result = new ExpandoObject();
var dict = (IDictionary<string,object>)result;
dict[name] = value;
然后可以將result
轉換為JSON。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.