Help Implementing Json, Jquery in asp.net

Jan 21, 2009 at 2:26 PM
Hi,
With jquery I want to pass a category to asp.net and return using Json a list of places under that category. First I will show you the code and then the questions. Here is the code
Client
$(document).ready(function() {
            $(".subcat").click(function(e) {
                e.preventDefault();
                JqueryAjax($(this).html());
                //alert("Hello world!");
            });
        });

function JqueryAjax(category) {
    $.ajax({
        type: "POST",
        url: "Test.aspx/AttractionsWithCategory",
        data: "{'category':'" + category + "'}" ,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            // Replace the div's content with the page method's return.
        alert(msg.d);
        } //end success
    }); //end ajax
}
Server
[WebMethod]
    public static string AttractionsWithCategory(string categoria)
    {
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        using (JsonWriter jsonWriter = new JsonTextWriter(sw))
        {
            jsonWriter.WriteStartObject();
            jsonWriter.WritePropertyName("Place");
            jsonWriter.WriteValue("Place1");
            jsonWriter.WriteEndObject();
        }
        return sb.ToString();
    }
Questions
  1. Is this the right way to return the Json "sb.ToString();"
  2. Using firebug I can see that the post request to the server is "{'category':'river'}" , but the response is {"d":"{\"Place\":\"Place1\"}"}; I just want to see a response like "{'Place':'Place1'}" without the "d" and the other stuff. Any suggestions, thanks.
Jan 28, 2009 at 7:05 PM
This is how .NET prevents malicious cross scripting attempts. All you need to do is eval your msg.d contents into a new var and you'll have your object.

success: function(msg)[
   var placeObj = eval("("+msg.d+")");
   alert(placeObj.place);
]