I have an asp.net-mvc page and in my javascript in my view, I have this code which works perfect:
MyView.aspx
<script type="text/javascript">
var apps = <%= new JavaScriptSerializer().Serialize(Model.Apps) %>;
SetupApplications(apps);
</script>
(Apps is a array of strings).
I now need to change this to be called from an ajax method. I tried a few things but neither seemed to work. I am passing back a string array from server side controller action like this:
return Json(new {
Apps = GetAppsStringArray()
});
and on the client side javascript callback I call the same method:
$.post("/MyController/MyAction", function (data) {
SetupApplications(JSON.stringify(data.Apps) }
, "json");
Do you see anything flawed in why these wouldn't be equivalent?
You are creating a JSON string from the object that was created by parsing the JSON string that you get in the response. As the SetupApplications
function doesn't take a JSON string in the first version of the code, it shouldn't do that in the second either. Just pass the object to the function without turning it into JSON again:
$.post("/MyController/MyAction", function (data) {
SetupApplications(data.Apps);
}, "json");