Alica Corwin Alica Corwin - 3 months ago 7
jQuery Question

Unable to Serialize HTML Form using jquery

Hello there i am a newbie in ASP.NET development.I am unable to get the correct serialize form using Jquery.you can see that asp hidden fields is attached to my serialize string

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.10.2.js" type="text/javascript"></script>
<script src="jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#button2").click(function () {
var form = $("#form1").serialize();
alert(form);

});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>
<asp:Button runat="server" ID="button2" Text="submit" />
<div>

</div>
</form>
</body>
</html>

Answer

The form serialization appears to be working correctly. It serializes the form into a URL format of name=value pairs. For example name=First%20Last&age=27.

Because you're using ASP.NET forms they have a hidden __VIEWSTATE field. That's why you're seeing __VIEWSTATE=SC20935uo236h2oth3li3h.... You shouldn't need to submit the viewstate because that's an ASP.NET-specific mechanism for tracking what state the forms are in.

You can exclude the __VIEWSTATE field from the serialization by using JQuery to select all inputs except __VIEWSTATE.

$('#form1').on('submit', function() {
    var serializedFields = $('input[name!=__VIEWSTATE]', this).serialize();
    console.log(serializedFields);
});

Open your browser's developer console (Ctrl+Shift+J on windows) to see the console.log() messages (this is far better than using alerts).

This works by listening for the form's submit event, then querying for all fields except __VIEWSTATE. Because we're inside the form submit event, this refers to the form, so we pass that as the context for our selector, hence the $('...', this).