ASP.NET MVC - Issue with CSS Class Name on ActionLinks
(
Jun 16 2008 - 02:49:02 PM by
Timothy Khouri) - [
print blog
post]
I've been getting into ASP.NET MVC recently, and I have to say, it's a beautiful thing. Being that it's incredibly new and beta (currently preview 3 is out), there are a few bugs that I've run into.
This one in particular has to do with how to add custom HTML attributes to your ActionLinks (which is basically a link to an MVC "page"). The method that you call to create a link is basically this:
<%= Html.ActionLink<"Tag">MyController>(c => c.SomeAction(), "Link Text" %>
This would build a link to the 'SomeAction' view on the MyController... controller :) Now, there are ways to build action links that are a little easier on the eyes, but I'm using this particular overload to show how to add HTML attributes to your link.
So, if you wanted to do some inline CSS, you would change the above code to the following:
<%= Html.ActionLink<"Tag">MyController>(c => c.SomeAction(), "Link Text",
new { style = "color: #f00;" } %>
ASP.NET MVC will automatically parse the "object" parameter at the end there and reflect all properties, then it will add them to your link. So the above code would build a link that looks something like this:
<a href="/MyController/SomeAction" style="color: #f00;">Link Text</a>
Where ASP.NET MVC Loses Me
This approach above seems very 'code cowboy' to me. There is no reason why the last paramter doesn't simply take a params array of name value pairs, or a dictionary, or something like that. Instead, we are now bound to only use HTML attributes that are valid C# (or VB if you're using that language) property names!
I realize this may seem a little dramatic... but while building my navigation, I wanted to add a simple "class='selected'" attribute to my link... and guess what... "class" is a key-word in C#. So this:
<%= Html.ActionLink<"Tag">MyController>(c => c.SomeAction(), "Link Text",
new { class = "selected" } %>
Doesn't compile, and now I'm sad.
Bear With Me
I realize the above complaint is minor... and I am really starting to like MVC, but this just shows me it's not a 100% product yet. I'm excited to see where it goes :)