Silverlight throws InvalidOperationException with Common_MethodFailed error when calling HtmlElement.SetAttribute for the "type" attribute

I was working on a Silverlight application the other day and needed to create and submit an HTML form to another ASPX page inside the website hosting the app.

To accomplish this, I was using the HtmlDocument.CreateElement, HtmlElement.SetAttribute and HtmlElement.AppendChild methods to set the whole thing up.

After deploying the application having success with Internet Explorer 9 (IE9), Chrome, etc. we tested on two virtual machines that had IE7 and IE8 and were met with errors and no form submission.

It turns out it was because I was trying to set the "type" attribute of the <input /> elements I was creating with the Silverlight methods after I'd called the AppendChild method.

IE7 and IE8 don't like a developer setting the "type" attribute after the element has been appended to the document and it will throw a JavaScript error which bubbles up to the Silverlight application and the user is shown an obscure InvalidOperationException error whose key is "Common_MethodFailed".

It made no sense to me, but I dug deeper until I could find the offending line.  I then tried an experiment with a XHTML/JavaScript page in the offending browsers to see if it was a Silverlight problem or a problem with the JavaScript engines of said browsers.

I ran into the same problem without Silverlight in the equation.  I wrote up a detailed article explaining it and have the experiment to try in different browsers yourself on my JavaScript Jedi website.

The problem can be solved by making sure you call AppendChild AFTER you set up all the properties/attributes on the HtmlElement, not before.

I hope this helps you avoid several hours of frustration.  :)
Happy Coding!