Return complex object from an AJAX call
Environment used: ASP.NET, jQuery
I have the following AJAX call:
var tempVar = JSON.stringify({plotID:currentId});
$.ajax({
type: "POST",
url: "testPage.aspx/getPlotConfig",
data: tempVar,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#xDimLbl').text(msg.xDim);
$('#bDimLbl').text(msg.bDim);
}
});
The code behind has the method getPlotConfi开发者_开发问答g(string plotID) defined as
public static string getPlotConfig(string plotID)
{
string x = "T1";
string b = "T2";
return Json(new { xDim= x, bDim= b });
}
Questions:
- When I do a build, I get the error: The name 'Json' does not exist in the current context Which namespace is amiss?
- Along with the two strings x and b, I would like to return a hash table whose key is a string and value is a list of comma separated strings. How do I do that and how to access each key value pair at the client side?
cheers
This could be referring to the Json method used in ASP.NET MVC controller. As your getPlotConfig
function is static you cannot use this method. You may take a look at PageMethods. Here's an example:
[WebMethod]
[ScriptMethod]
public static object getPlotConfig(string plotID)
{
var hash = new Dictionary<string, string>()
{
{ "key1", "valueA,valueB" },
{ "key2", "valueC,valueD" },
};
var x = "T1";
var b = "T2";
return new { xDim = x, bDim = b, hash = hash };
}
And in javascript:
success: function(msg) {
$('#xDimLbl').text(msg.d.xDim);
$('#bDimLbl').text(msg.d.bDim);
for(var key in msg.d.hash) {
var value = msg.d.hash[key];
// Do something with key and value...
}
}
精彩评论