Reading Serialized JSON object in Java Script Function

ASPDEV
ASPDEV used Ask the Experts™
on
Hello Experts,

I'm new to MVC devlopment, I was using Viewbag to pass the data from my controller to JS(jquery function). I want to know how can I read the List data and then assign to my grid. This is the sample code, I was getting error while reading the ViewBag.MyList in my JS function. How can I do this so I can get the list object. Later part once I get the list object, then I will bind the data with the grid.

Controller
public async Task<ActionResult> TestData(
string resp = "";
 var test = new List<Tuple<int, string>>();
test.Add(new Tuple<int, string>(1, 'R1'));
test.Add(new Tuple<int, string>(2, 'R2'));

if (test.Count > 0) {
ViewBag.MyList= Newtonsoft.Json.JsonConvert.SerializeObject(test);
}

resp = "test";
}

Open in new window


JavaScript
$.ajax({
        type: 'post',
        url: url,
        processData: false,
        contentType: false,
        data: files,
        success: function (response) {

 if (response == 'test')
{
var testList= JSON.parse('@Html.Raw(ViewBag.MyList)');
}
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Hi
Use below function to convert List to JSON in Controller:
string DictToJson(Dictionary<int, List<int>> dict)
{
    var allValues = dict.Select(d =>string.Format("\"{0}\": [{1}]", d.Key, string.Join(",", d.Value)));
    return "{" + string.Join(",", allValues) + "}";
}

Open in new window


OR
if you are using JSON.NET then use:
return JsonConvert.SerializeObject(<your_dictionary_object_here>);

Open in new window


Then you can use below code (JavaScript) in view:
success: alert(JSON.stringify(response));

Open in new window

Author

Commented:
It worked

Author

Commented:
Thanks Mrunal. It worked

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial