我正在为我的MVC控制器中的Jquery flot生成数据,并且希望使用更复杂的结构,以便能够更改每个条的颜色等。如何将JSON数据从MVC4传递到Flot而无需编写适配器
要做到这一点我需要传递data structure that looks following
{
label: "y = 3",
data: [[0, 3], [10, 3]]
}
我传递数据时,它是简单的数组通过简单地获取数据和塑造它像下面
var data = topAgents.Select(agent => new List<object>
{
agent.User != null ? string.Format("{0}", agent.User).Replace("SAGANTGB\\", "") : null,
agent.Amount
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
没问题
,并在JavaScript方面:
function onAgentDataReceived(series) {
$("#agents").empty();
$.plot("#agents", [series], { bars: { show: true, barWidth: 0.6, align: "center" }, xaxis: { mode: "categories", tickLength: 0 } });
}
但是现在我似乎无法能够将数据塑造成这样,将适合什么$ .plot期待的结构。
到目前为止,我曾尝试:
的键值对:
var grouped = result.GroupBy(o => o.CREATE_USER_ID).Select(agent => new
{
data = new KeyValuePair<string,int>(
agent.Key != null ? string.Format("{0}", agent.Key).Replace("SAGANTGB\\", "") : null, agent.Count()
),
color = "yellow"
}).ToList();
对象与属性:
var grouped = result.GroupBy(o => o.CREATE_USER_ID).Select(agent => new
{
data = new { A=
agent.Key != null ? string.Format("{0}", agent.Key).Replace("SAGANTGB\\", "") : null, B = agent.Count()
},
color = "yellow"
}).ToList();
名称值集合
var grouped = result.GroupBy(o => o.CREATE_USER_ID).Select(agent => new
{
data = new NameValueCollection
{{
agent.Key != null ? string.Format("{0}", agent.Key).Replace("SAGANTGB\\", "") : null, agent.Count().ToString()}
},
color = "yellow"
}).ToList();
匿名对象数组
var grouped = result.GroupBy(o => o.CREATE_USER_ID).Select(agent => new
{
data = new object[] { agent.Key != null ? string.Format("{0}", agent.Key).Replace("SAGANTGB\\", "") : null, agent.Count()},
color = "yellow"
}).ToList();
但他们没有飞过
恕我直言简单data = new object { agent.Key, agent.Count()},
应该工作,但它在构建失败:Error 16 Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
。
我可以在重新获取JS后的数据,但想避免这个不必要的步骤。
如何将数据从MVC传递到JavaScript而不必在JS端重新塑造它?