Because I was stumped on the various ways to build links (hyperlinks)with the new MVC framework, I thought I would save others the pain that I went through and show the various ways to build links. You can also get this information by watching Scott Hanselman's screencasts on the frameworks as well.
There are 3 different ways to build links in the new framework. Each one is effective, but each has its own pros/cons.
- The quick and dirty way
The MVC framework is based on HTML, so you could simply do the following:
<a href="/SomeController/SomeAction/<%= o.Value %>"">Link</a>
This method has one huge, glaring issue. It is not refactor friendly. If you ever wanted to change the name of the controller being called, or the action method being called you would have to do a find and replace.
This method is pure evil as it is littered with 'magic' strings.
- The better way
Another way to create link is to use the Html helper classes that are provided as part of the MVCTool kit (now just part of the MVC framework). The helper method we want to use is the Html.ActionLink method. The following is an example:
<%=Html.ActionLink("Edit", "EditAction", new { id = o.Value } ) %>
This method is better then the one above as you do not have to worry about the controller as it is implied (assuming you don't want to use a different controller then the one in the current path). However, this still has a refactor issue. The 2nd param is the name of the action (method) being called on the controller. If you need to change this for any reason you again would have to do a find and replace.
- The best way (In my opinion)
The last option also uses the Html helper classes, but this time we are going to use a Lambda expression. The following is an example:
<%=Html.ActionLink<MyController>(c => c.Action( o.Value ), "Edit" ) %>
This method is the best in my opinion because it is the only one that is strongly typed. This option may cause some people some pain because they will have to learn/understand lambda expressions, but that is something well worth learning.
With this method, since the controller being used is strongly typed, the method name and parameter values are all typed strongly typed, refactoring should be a breeze.
Remember it is always better to have compile time errors then runtime errors due to your refactoring.
I hope this helps someone. I know I was a little stuck till I watched Scott's video.
BTW, this post could also apply to most of the other HTML helper methods. Many of them are able to be typed because they use Lamba expressions.
Till next time,
Posted
03-06-2008 7:34 PM
by
Derik Whittaker