Ray K.
Ray K.

Reputation: 2521

How to deserialize in C# something that was serialized in JQuery?

. .

It's been a while since I've done this, and I'm trying to shake off the rust.

I'm trying to set up an AJAX structure in ASP.NET using VS2010.

I have a JQuery form submit that looks something like this (greatly simplified for example purposes):

function FormSubmit () {
    $.post('SomeHandler.asmx/SomeFunction', 
        $("#form1").serialize(), 
        function(data) {some data handler}
    );
}

My "SomeHandler.asmx/SomeFunction" is a C# function that takes my form data and processes it.

To my knowledge, the SomeHandler.asmx assumes XML deserialization, but the JQuery serializes it as an HTML encoded string, not as XML.

I suppose to use an analogy, one side is speaking in English, but the other side is expecting to hear French.

How do I get around this? (For example purposes, let's say my form has a text field -- we'll call it "txtField", and a drop-down list -- let's call it "lstDropDown".)

Thanks in advance for your help!

Upvotes: 0

Views: 1227

Answers (1)

pwnyexpress
pwnyexpress

Reputation: 1016

In your asmx file make sure you use the following attribute flags on your web methods that accept and respond with json:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SomeWebMethod() 
{
  //blah
}

Also, make sure the web service class has the follow attribute flag:

[System.Web.Script.Services.ScriptService]
public class MyWebService : System.Web.Services.WebService
{
...
}

One last thing: if you're serializing the data on the client side, you need to use the following ajax setup:

 $.ajaxSetup({ contentType: "application/json; charset=utf-8" });

Upvotes: 1

Related Questions