MVC ActionLink Setting Custom Attributes With Class

Lately I have finally been working on an ASP.NET MVC project using the Razor ViewEngine. I do like the MVC programming style, but just as I suspected when I first learned about MVC there is a learning curve. One of the things I am getting use to is using the Html.ActionLink helper function. This function generates a properly formatted Url pointing to another (hopefully) valid end point in the site.

The method has 10 overloads and to someone new to MVC this can be sort of intimidating. The most common overload passes the display text and the action name. This will generate a link to another action or end point on the same controller used to generate the current page. So the following code will generate a link to the Edit action on the existing controller.

@Html.ActionLink(

"New Widget"

,

"Edit"

);

The resulting link would look something like: /Widgets/Edit

If you want to create a link to another controller add the controller name to the function like this:

@Html.ActionLink(

"New Widget"

,

"Edit"

,

"Widgets"

)

This will generate the same link as above no matter where you are in the site.

The next overload I have found useful lets you append RouteValues or parameters to the Url. Here you need to add a RouteValueDictionary to the list of function parameters. Thanks to anonymous classes you can do this with a simple new {paramName = paramalue} syntax.

@Html.ActionLink(

"Widget"

,

"Edit"

,

"Widget"

,

new

{ Id =

"12345"

})

Now the Url generated would look like: /Widgets/Edit/12345. Your controller action would be responsible for processing the input value.

public

ActionResult Edit(

string

Id) {

//Do something here



return

View();
}

Finally I found I you can add attributes to the rendered anchor tag, which is super useful when you are trying to control the style and creating AJAX code. Again you add a Dictionary of attributes and their values to the list of ActionLink parameters. Here I am adding the CSS class names and a custom Id attribute.

@Html.ActionLink(

"New Widget"

,

"Edit"

,

"Widget"

,

new

{ Id =

"New"

},

new

{ @

class

=

"edit-link list-link"

, Id=

"12345"

})

Note, class is of course a reserved word so you need to prepend it and any other C# reserved word with an @. Next you do not have to hard code the value '12345' like I did in this sample. You could also use a variable, Id=@ViewBag.Id is also fine.

So the finally anchor tag should look like:

<

a

href

="/Widgets/Edit/12345"

class

="edit-link list-link"

id

="12345"

>

Edit

</

a

>


These are the ActionLink overloads I have found most useful. I hope this helps other MVC newbies get off to a good start.

Share This Article With Your Friends!