将JsonResult与jQuery一起使用

时间:2014-03-17 17:49:15

标签: jquery asp.net-mvc json model-view-controller

我需要为jQuery插件返回一个Json。

需要像这样:[{ "name": "Testing", "desc": "OB-2014-0202", "values": [{ "Status": 2, "from": "\/Date(1391295600000)\/", "to": "\/Date(1392505200000)\/", "customClass": null, "label": "DO NOT DELETE" }] }],

但JsonResult返回

[{ "name": "DO NOT DELETE", "desc": "OB-2014-0202", "values": { "Status": 2, "from": "\/Date(1391295600000)\/", "to": "\/Date(1392505200000)\/", "customClass": null, "label": "DO NOT DELETE" } }],

注意“values”节点缺少[]。

以下是Json的生成方式:

public class JsonOrdersGantt
{
    #region Constructors

    public JsonOrdersGantt(IEnumerable<Order> listOrders)
    {
        Orders = new List<JsonOrderGantt>();

        foreach (var order in listOrders)
        {
            Orders.Add(new JsonOrderGantt(order));
        }
    }

    #endregion

    #region Properties

    public List<JsonOrderGantt> Orders { get; set; }

    #endregion
}

public class JsonOrderGantt
{
    #region Constructors

    public JsonOrderGantt(Order order)
    {
        name = order.ordBrand;
        desc = order.ordPO;
        values = new JsonOrderGanttValues(order);            
    }

    #endregion

    #region Properties
    public string name { get; set; }
    public string desc { get; set; }
    public JsonOrderGanttValues values { get; set; }

    #endregion
}

public class JsonOrderGanttValues
{
    #region Constructors

    public JsonOrderGanttValues(Order order)
    {
        from = order.ordStartDate;
        to = order.ordEndDate;
        customClass = order.ordStatus.ToString();
        label = order.ordBrand;
    }

    #endregion

    #region Properties

    public DateTime? from { get; set; }
    public DateTime? to { get; set; }
    public string customClass  { get; set; } //: "ganttRed"
    public string label  { get; set; }
    #endregion
}

函数的调用:

public JsonResult GetGanttOrders()
{            
    var repository = new OrderRepository();
    var models = repository.GetGanttOrdersList();

    return Json(new JsonOrdersGantt(models), JsonRequestBehavior.AllowGet);
}

任何想法我怎么能用[]获取Json的值? (或者使用jQuery使其无需[])

Thanx很多

2 个答案:

答案 0 :(得分:0)

尝试

values = new List<JsonOrderGanttValues> { new JsonOrderGanttValues(order) };

答案 1 :(得分:0)

使用jquery

遍历树,如下所示
var obj = [{ "name": "DO NOT DELETE", "desc": "OB-2014-0202", "values": { "Status": 2, "from": "\/Date(1391295600000)\/", "to": "\/Date(1392505200000)\/", "customClass": null, "label": "DO NOT DELETE" } }];
console.log(obj[0].name);
console.log(obj[0].desc);
console.log(obj[0].values);
console.log(obj[0].values.Status);
console.log(obj[0].values.from);
console.log(obj[0].values.customClass);