How to serialize ASP.NET web form using jQuery

In this post, find how to serialize ASP.NET web form using jQuery. jQuery provides a very useful function jQuery.serialize() which encodes a set of form elements as a string.

What is serialize and why do we need?

Serialize is a way to combine your form values and create a single string which then can be used to send to server for ajax request. It is useful when your form is huge and you need to post all the form input value to server using ajax. Creating such string manually is not desired. Serialize can help you with this.

Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked.

How to use it?

Consider a following form with 3 input controls with a submit button.

<form action="#" id="form1">
     First name: <input type="text" name="first name" /><br />
     Last name: <input type="text" name="last name" /><br />
     Email: <input type="text" name="email" /><br />
     <input type="submit" value="send" id="btnSubmit" />
</form>

So when we serialize this form, so following serialize string is returned using "$("#form1").serialize();"
"first+name=jQuery&last+name=byexample&email=jquerybyexample%40gmail.com"

You can easily include particular set of controls while serializing the form. For example, you want to include only input controls not select controls.

function SerializeForm()
{
   var sValue = $("#form1")
               .find("input")
               .serialize();
   return sValue ;
}

Above code will only serialize input controls only, ignoring all other controls.

What about ASP.NET Webform?

With ASP.NET Webform, there is an issue. As to maintain states between postback, ASP.NET adds two extra input controls with ID "__VIEWSTATE" and "__EVENTVALIDATION". And we don't want to serialize these two controls input. We need to ignore them otherwise your serialize string will break and code will fail. So use ".not()" selector to ignore these 2 controls.

function SerializeForm()
{
   var sValue = $("#form1")
               .find("input,textarea,select")
               .not("#__VIEWSTATE,#__EVENTVALIDATION")
               .serialize();
   return sValue ;
}

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...