1
votes

I need get a jquery serialized data with c# webforms code behind i try this way:

jQuery.ajax({
            type: "POST",
            url: "book_de_acoes.aspx/salvarSimulacaoAutomatica",
            data: JSON.stringify({ form: jQuery("#aspnetForm").serialize() }),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (callback) {
                alert(callback);
            }
        });

c# code behind:

[WebMethod(true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static bool salvarSimulacaoAutomatica(string form)
{
    try
    {
        System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
         var formData = js.Deserialize<object>(form);
    }
    catch(Exception e)
    {
    }
    return true;
}

but aways get a error:

System.ArgumentException: Invalid JSON primitive: ctl00. at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input) at PortalSuvinil.admin_portal.book.book_de_acoes.salvarSimulacaoAutomatica(String form)

how is the right way to get this data?

1
What sting has your parameter? - kostas ch.

1 Answers

1
votes

The issue here is that jQuery.serialize() does not create JSON. It creates standard form url encoded data that looks like this:

'single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1'

This will not translate to any meaningful JSON since it's just a giant string.

The trick is to use jQuery.serializeArray() instead, which will produce an object that can be serialized as JSON.

[{name:'single',value:'Single'},{name:'multiple',value:'Multiple'}]

This link can show you how to handle that data in a PageMethod: http://www.asp.net/ajaxlibrary/jquery_webforms_post_data_to_pagemethod.ashx