Roni Axelrad Roni Axelrad - 1 month ago 17
Javascript Question

Why my WebMethod always returns JSON?

First my apologies if this is a noob question, it's not my area .

I have a WebMethod, Which return String (string table=""), But the Ajax return function
always see that as an JSON Object looks like '{"d":{ ...}}" . My Question is WHY
I get a JSON back, even though my Ajax is expecting "text" ?

WebMethod :

[WebMethod()]
public static string TestAjax(string val)
{
string sSql = ConfigurationManager.AppSettings["GetMiToSend"];
sSql = sSql.Replace("$Company$", val);
string table = "";
try
{
DbCommand command = m_connection.CreateCommand();
command.CommandText = sSql;
command.CommandType = CommandType.Text;
DbDataReader oDataReader = command.ExecuteReader();
int count = 0;
if (oDataReader != null)
{
count = oDataReader.FieldCount;
}
table = "<table>";
while (oDataReader.Read())
{
table += "<tr>";
for (int i = 0; i < count; i++)
{
table += "<td>" + oDataReader.GetValue(i) + "</td>";
}
table += "</tr>";
}
table += "</table>";
}
catch (Exception ex)
{
Console.Out.WriteLine(ex.Message);
}
return table;
}


My Ajax function :

$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/Default.aspx/TestAjax") %>',
data: JSON.stringify(toSend),
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (data) {
alert(data);
$('div#container div#content').html(data.d).show(1000);
$('div#container div#showContent').hide();
$('div#container div#content').addClass('rwd-table');
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});

Answer

I'm pretty sure you can't return a string from a WebMethod. I tried without success to confirm my assertion. So change your code to return a json instead of a string.

MS Developer Network: How to: Use the WebMethod Attribute:

Attaching the WebMethod attribute to a Public method indicates that you want the method exposed as part of the XML Web service.

Return a json in your WebMehod:

List<object> jsonObject = new List<object>();

jsonObject.Add(new
{
    htmlTable = table
});

return (new JavaScriptSerializer()).Serialize(jsonObject);

Change your ajax to return a json:

dataType: "json"

Then access your json object and your html table:

var dataParsed = $.parseJSON(data.d);
var htmlTable = dataParsed[0].htmlTable;
// Do your actions with your htmlTable. Append to an element or other action.
Comments