Using JsonResult with jQuery

68 views Asked by At

I need to return a Json for a jQuery plugin.

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

but JsonResult return

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

Note the [] missing for the "values" node.

Here is how the Json is generated :

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
}

And the call of the function :

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

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

Any Idea how I can get the Json with [] for the values? (Or using jQuery to get it works without [])

Thanx a lot

2

There are 2 answers

0
beautifulcoder On

Try

values = new List<JsonOrderGanttValues> { new JsonOrderGanttValues(order) };
0
Faiz Mohamed Haneef On

Traversing tree as below using 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);