Thursday, June 4, 2009

Code-Gen Ideas for MVC

This is a pretty cool idea I may try in our next MVC app:

http://blogs.msdn.com/davidebb/archive/2009/06/01/a-buildprovider-to-simplify-your-asp-net-mvc-action-links.aspx

I think I would prefer T4 instead of build providers, but basically this looks at all the Controllers and Actions and code-generates extension methods to help when creating links. You can then do:

<%=Html.ActionLinkToHomeIndex(“Home”)%>

Instead of

<%=Html.ActionLink(“Home”, “Index”, “Home”)%>

The later has always bothered me, because if your action or controller names change, this still compiles and doesn’t get caught until somebody clicks the link.

There’s probably more that could be done similarly, like generating methods for each partial view:

<%Html.RenderPartialEmployeeMenu(model);%>

Or strong-typed ActionResult methods:

return RedirectToHomeIndexView(model)

Basically, anywhere that MVC relies on a "Magic String" for Action or Controller names, this approach would help make for cleaner and better code.

No comments: