Perhaps you've seen complex solutions for moving ASP.NET-generated hidden fields (__EVENTVALIDATION, __EVENTTARGET, __EVENTARGUMENT, etc...) to the bottom of the form. Forget it. Here's the easy way to do it -- in a single line of code.
This article is inspired by a recent blog post at Sb2DevelopersBlog, where my friend Yoann writes about moving hidden fields for event validation to the bottom of the page using a heavy-duty custom HttpModule. As Yoann points out, this can be helpful for search engine optimization, as the crawler can parse your content without having to wade through a ton of gobbledygook first.
The solution he presents is actually quite clever, but pretty complicated. I've seen others as well, like those which involve overriding the Render method and using regular expressions to match the hidden form tags. Again, too complicated.
Did you know that, with the release of the .NET Framework 3.5 SP1, there's a much, much easier way?
In your application's configuration file (web.config):
Yeah, that's it. Seriously. But before you go doing this, you might want to read a little bit further...
Is This a Good Idea?
Maybe, maybe not.
As pointed out, moving hidden fields to the bottom can help searchbots index your content more easily, and will also make the client-side rendering a bit quicker too, both of which are big plusses.
But, as with many optimization techniques, there's a potentially serious downside as well. You see, there's a good reason ASP.NET 3.5 renders hidden form fields at the top by default. By doing this, it ensures that all the information in these fields gets posted to the server in case if a user get impatient and tries to post the form before the page finishes loading. In the case where these hidden fields are rendered at the bottom, if a postback is performed before the page fully loads, it will usually cause the following error:
Invalid postback or callback argument.
This can be especially troublesome in AJAX scenarios, or when using third-party controls that render hidden fields of their own. The only way I know of to determine which pages might cause trouble is to test them individually and see what happens.
There are a few other things you'll want to keep in mind when using this property:
- Even though the property is called "RenderAllHiddenFieldsAtTopOfForm," it won't affect hidden fields that you create, only system-generated ones.
- This property is applied to all the site's pages, and can't be overridden at the page level.
- I've done a bit of experimenting and as far as I can tell, the __VIEWSTATE hidden field still renders at the top of the form, regardless of the property's setting.
- This is supported by .NET Framework versions 3.5 SP1, 3.0 SP1, and 2.0 SP1.
Hopefully, those of you who are interested in overriding ASP.NET's default hidden field behavior will find this information useful.