Wednesday, April 15, 2009

Quick ASP.NET MVC Tip: Double Check Html vs =Html

I keep running into this silly error in my ASP.NET views:

The best overloaded method match for 'System.IO.TextWriter.Write(char)' has some invalid arguments

The root cause always takes me a few minutes to realize, but has to do with HtmlHelper extension methods. Some return strings, as in <%=Html.TextBox(...)%>.  Others output directly to the page, as in <%Html.RenderPartial%>.  If you try to use the
"=" when it's not needed, you'll get the error above.  Just remove the "=" and it's fixed!

To explain furthur, every time you view a page in ASP.NET MVC or WebForms, ASP.NET compiles the markup into .NET code.  So <%=Html.TextBox(...)%> behind the scenes becomes something like output.Write(Html.TextBox(...)).  When you write <%=Html.RenderPartial(...)%>, behind the scenes, this becomes output.Write(Html.RenderPartial(...)).  Since Html.RenderPartial doesn't return a string, and the output.Write method is looking for a string, the application fails with the above error.

No comments: