Shahin
Shahin

Reputation: 12861

Using jQuery Serialize in ASP.NET

what is the usage of jQuery Serialize API in ASP.NET ? how can we use it ? Is it possible to convert serialized object to .NET strong type object? Or map the serialized object to into .NET equivalent object? for example we have two field in a 'member' table. Name , Age. so we have these properties in Member Entity ;

    public string Name { get; set; }
public string Age { get; set; }

And we have these codes in our presentation layer :

       <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
        <asp:Button ID="btnSave" runat="server" Text="Button" />

When I serializing form using this code :

$.fn.serializeNoViewState = function()
{
    return this.find("input,textarea,select,hidden")
               .not("[type=hidden][name^=__]")
               .serialize();    
}

the Serialized object will be like this :

ctl00%24MainContent%24txtName=Pitter&ctl00%24MainContent%24txtAge=20

so is this string or JSON object? I think its string. and now what are the benefits of this Serialized output for us? I know that we are able to pas this output to server using jQuery AJAX. but how can we use it Server Side?

Upvotes: 1

Views: 4387

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039488

As the documentation explains it the .serialize() method is passed a form DOM element and it converts it into a URL encoded string of key/value pairs that you could pass to the server. But if you want to work with strongly typed objects in ASP.NET you could take a look at Page Methods. For example suppose that you have defined the following type:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

you could then have a page method:

public partial class _Default : Page 
{
    [WebMethod]
    public static string Process(Person person)
    {
         // TODO: do some processing
         return DateTime.Now.ToString();
    }

    ...
}

and to invoke this method using jQuery and JSON request:

$.ajax({
    type: 'POST',
    url: 'Default.aspx/Process',
    data: JSON.stringify({
        name: 'foo', // you could fetch those values dynamically
        age: 25
    }),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(msg) {
        // msg.d will contain the object returned from the server
        // in our example it's a simple string but you could use any
        // complex type you like (well almost any, it must be JSON serializable)
        alert(msg.d);
    }
});

Upvotes: 2

Related Questions