我正在进行ajax调用以检索从查询返回的JSON数据。我的JSON正在返回以下内容(准确地说):
[{
"label": "",
"value": "2302"
}, {
"label": "9 - Contract set-up in EPICOR",
"value": "2280"
}, {
"label": "2 - Verify PO received",
"value": "2279"
}, {
"label": "7 - Review quote and prepare team for meeting",
"value": "2281"
}]
但我需要它才能真正回归:
{
"options": {
"logan_dvprTasks.taskID": {
[{
"label": "",
"value": "2302"
}, {
"label": "9 - Contract set-up in EPICOR",
"value":"2280"
}, {
"label": "2 - Verify PO received",
"value":"2279"
}, {
"label": "7 - Review quote and prepare team for meeting",
"value":"2281"
}]
}
}
我生成JSON的代码是:
public IEnumerable<updatetasks> GetAllItems(string dvprid)
{
string stringSQL = "sqlStatement goes here";
string connString = ConfigurationManager.ConnectionStrings["loganWebConn"]
.ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(connString))
{
sqlConnection.Open();
using (SqlCommand cmd = sqlConnection.CreateCommand())
{
cmd.CommandText = stringSQL;
cmd.CommandType = CommandType.Text;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var updatetasks = new updatetasks();
updatetasks.label = reader["taskName"].ToString();
updatetasks.value = reader["taskID"].ToString();
yield return updatetasks;
}
}
}
}
}
如何修改我的C#代码以在JSON对象的开头添加这两个项目?
答案 0 :(得分:1)
通过返回您想要的对象。
将您的ajax调用更改为此方法并将其返回。
public object MyCall(string dvprid)
{
return new
{
options = new
{
logan_dvprTasks = GetAllItems(dvprid)
};
};
}
请注意.
(点)对C#标识符无效,因此我只是logan_dvprTasks.taskID
致电logan_dvprTasks
。
如果您的意思是taskID
是logan_dvprTasks
的属性,那么生成的JSON就是
{"options":{"logan_dvprTasks":{"taskID":[...]}}}