A while ago I wrote a post on using jQuery Serialize against a fieldset(s) for the use on ASP.Net Web Forms. Since Web Forms only have one form, us ASP.Net Developers miss out on all the joy of the jQuery Functionality. (the post has generated a lot of traffic to my blog too.)
Something I have been meaning to add to that post however, is what we do after we have grabbed all the fieldset field elements. One problem is INamingContainer ID’s on all the fields, the second thing, is making an AJAX request.
When making AJAX requests on website’s I personally don’t like the idea of calling a Web Service or WCF Service from JavaScript, or using those old Page Method things (not even sure people still use those).
Neatest way I’ve found, which I’ve been using for about 5 years now, is HTTPHandlers.
In this post I’m gonna show how to fix up the ClientID’s, and later I’ll post about using HTTPHandlers.
Removing ClientID’s
Using the same project I posted last time, I’ve taken the fieldsets and moved them into their own User Control, and changed the form elements to ASP.Net Server Controls. This results in HTML rendered like:
<fieldset class="fsLoginForm">
<legend>Login Fieldset</legend>
<ul>
<li>Email: <input name="ccTestForm$txtEmail" type="text" id="ccTestForm_txtEmail" /></li>
<li>Password: <input name="ccTestForm$txtPassword" type="text" id="ccTestForm_txtPassword" /></li>
</ul>
</fieldset>
When I run the page to see the serialized data we get:
Yucky yucky form names. Makes it impossible to use this data for anything, anywhere we post it, we wont be able to get the data without knowing the INamingContainer its sitting in, and even if you did know, it can’t be reused, if you put the form on another page the names could be completely different.
Good thing is, once we clone the fieldsets to serialize them, we can rename all those field names relatively easily.
//Clone the fieldset into the new form.
$('#form-to-submit').html($(fieldsetName).clone());
//Rename all the field 'name' attributes
$('#form-to-submit').find('input, select, textarea').each(function(i, e)
{
var newName = $(e).attr('name').substring($(e).attr('name').lastIndexOf('$') + 1);
$(e).attr('name', newName);
});
//Serialize the data
var data = $('#form-to-submit').serialize();
I’ve used the same function from the previous post, just included a loop after the clone, before the serialize, basically it loops through each form element, finds the last part of the name, and reassigns it back to the element.
Running the same piece of code again produces:
Now we have nice clean names to post somewhere.
Thats all for now.