Tamindyguy Tam
Tamindyguy Tam

Reputation: 51

How to de-serialize C# list object and iterate through it to parse values in an Ajax success response

I call an action method via AJAX and return a list object, I am having difficulty in de-serializing the response in JQuery. I try to iterate through the repsone via $.each function but I get NULL. I know for sure data returned contains an object.

    [HttpPost]
    public JsonResult ToolTips(string viewName)
    {
        List<ToolTipMvc.Models.ToolTipMvcModel> result = ToolTipMvc.Models.ToolTipMvcModel.GetToolTip(viewName);
        var y = result;

        JavaScriptSerializer jss = new JavaScriptSerializer();

        string output = jss.Serialize(result);

        return Json(output);
    }

public static List<ToolTipMvcModel> GetToolTip(string viewName)
{
    List<ToolTipMvcModel> items = new List<ToolTipMvcModel>();
    //items.AddRange(toolTipIds.Select(s => GetToolTip(s)));

    ToolTip tp = new ToolTip();

    ToolTipMvcModel item = new ToolTipMvcModel();
    item.Description = "list item 1";
    item.Field = "ctrlOne";

    ToolTipMvcModel item2 = new ToolTipMvcModel();
    item.Description = "list item 2";
    item.Field = "ctrlTwo";

    items.Add(item);

    return items;
}  
$.ajax({
        type: 'POST',
        url: toolTipsUrl,
        cache: false,
        datatype: "html",
        data: { viewname: "runCreate" },
        success: function (data) {

alert(data);

                        data = JSON.parse(data);
                        alert(data);
                        $.each(data, function (dt) {

                            var mydata = data.Field;

                            alert(mydata);

                        });

}

EDIT

When I alert the data I see the JSON being returned for instance

[{"Field: "ctrlTwo", "Description":"List item 2"},{"Field: "ctrlTwo", "Description":"List item 2"}]

but when I use JSON.Parse(data) or $.parseJson(data) I see object object. I just want interate through and populate some text areas on the page

Upvotes: 0

Views: 2275

Answers (1)

nick_w
nick_w

Reputation: 14938

First of all, there is no need to explicitly use the JavaScriptSerializer yourself. The call to Json will serialize it for you, so instead have your controller method look like this:

[HttpPost]
public JsonResult ToolTips(string viewName)
{
    List<ToolTipMvc.Models.ToolTipMvcModel> result = ToolTipMvc.Models.ToolTipMvcModel.GetToolTip(viewName);

    return Json(result);
}

Doing this also means that you shouldn't need to perform any explicit JSON.Parse or $.parseJson.

In your success handler, you should be able to iterate through the results as follows:

success: function(data) {
    for (var i = 0; i < data.length; i++) {
        var item = data[i];
        console.log(item.Description);
        console.log(item.Field);
    }
}

Upvotes: 2

Related Questions