Tuesday, April 1, 2008

Whither form posts, Safari?

Now, in the "code" department...

I'm writing this for the benefit of the web-at-large, as nobody else appears to have commented on this behavior in my Googling.

Say you have an ASP.NET form with a FileUpload (<input type="file">) element in it. You leave the element blank and submit the form.

Internet Explorer and Firefox both send all of the form elements to the server, with no file.

Safari, on the other hand, sends an empty form post.

That makes ASP.NET sad, as none of the hidden ViewState fields are sent. Which means that your Button_OnClick bindings won't work, because they rely on the ViewState to know what just happened.

Here's my solution: for Safari, remove any blank file elements before the form is submitted.

The problem exists on both Safari 2.0.3 for OS X and Safari 3.1 for Windows.

This solution should work, but is not tested as written (I changed it to an anonymous function for this blog post). It requires Prototype.js.


Page.RegisterOnSubmitStatement(
"fixSafariSubmits",
@"(function() {
if (Prototype.Browser.WebKit) {
var pageForm = document.getElementsByTagName('form')[0];
var inps = Form.Methods.getInputs(pageForm, 'file');
inps.each(function(inp) {
if (inp.value == '') Element.remove(inp);
});
}
return true;
})()");

No comments:

Website Counter