I followed the instructions here Problem performing Ajax call from ASP.NET MVC2 app, and read about JSON. I searched a lot but didn’t find an answer. I use the following code:
view:
<script type="text/javascript">
var userName = $("#userName").val();
$.ajax({
type: 'POST',
url: '/Home/PgAJAXTest',
data: {
q: 'Test1',
s: 'Test2'
},
success: function (bbb) {
alert(bbb.Val13);
},
error: function (msg) {
alert("error");
}
});
</script>
ASP.NET MVC controller code is:
[HttpPost]
public JsonResult PgAJAXTest(string q, string s)
{
var a = Json(new { Val13 = " TEST " });
return a;
}
The problem is that I get "undefined".
If I change alert(bbb.Val13); to alert(bbb); I get {"Val13":" TEST "}
I suppose it has something to do with the controller not returning the JSON exactly in the format that JSON expects.
You re getting a string response.
Use something like
Since you are using jQuery, you can use
jQuery.parseJSONto parse the string.