Tim Scott's Blog

February 5, 2009

Eliminate Magic Strings In Javascript With MvcContrib.FluentHtml

Filed under: FluentHtml, MS MVC — Tim Scott @ 3:27 am

MvcContrib.FluentHtml provides a library of HTML helper methods that use expressions with strongly typed views to generate HTML elements. Not too long after that MS MVC beta introduced HtmlHelper<T> which allows users to create extension methods that use expressions in the same way.   The benefits are obvious.  By trading magic strings for expressions we gain compile time checking, better refactoring, etc.

So this:

<%=this.TextBox(x => x.User.FirstName)%>

Generates this:

<input type="text" name="User.FirstName" id="User_FirstName" value="Joe"/>

This is very nice, but what about all the other magic strings in our view?  I’m talking of course about Javascript. Does this look familiar?

$('#User_FirstName').change(doSomething);

Doh!  We just can’t escape those magic strings. Or can we?  How about this?

$('#<%=this.IdFor(x => x.User.FirstName)%>').change(doSomething);

MsMvc.FluentHtml has introduced IdFor and NameFor. Okay, so we won’t eliminate all magic string in Javascript but perhaps quite a few. Perhaps we give up a tiny bit of readability, but I think it’s worth it to stop fretting whether some refactor is going to break a bunch of Javascript.

I owe credit to Jimmy Bogard for planting this idea in my mind in one of his tweets.

Create a free website or blog at WordPress.com.