Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add a CSS class name to an ASP.NET MVC 3 Url.Action link?

In ASP.MVC 3 or 4 (using Razor), how do you apply a CSS Class to a Url.Action() helper method? Is it possible?

Desired outcome:

<a href="home\index?page=2" class="FOO">BAR</a>

I have gotten this far:

@Url.Action("Index", "Home", new { page })

UPDATE: Thanks all. I made a couple of mistakes that I should clarify for future readers (most likely myself). I wish I could give more than one of you credit.

a) new { page } - do not do this. It will produce undesired output. I meant: ViewBag.page or ViewBag.pageNum

b) As a few of you pointed out, I needed Html.ActionLink() not Url.Action() which I had been using successfully until I switched to generating the full tag, not just the url.

I confirmed that the following works as desired:

@Html.ActionLink("BAR", "Index", "Home", new { ViewBag.PageNum }, new { @class = "FOO" })
like image 815
Dan Sorensen Avatar asked Dec 01 '22 06:12

Dan Sorensen


2 Answers

Url.Action does not create any html element, it only creates a URL, which is why it's called Url.Action, and not Html.Action... (Html.Action is something totally different).

If you want css on a link that you use Url.Action on, just do this:

<a href="@Url.Action("Action", "Controller")" class="myclass">My Link<a>

Alternatively, you can use Html.ActionLink

@Html.ActionLink("My Link", "Action", "Controller", null, new { @class="myclass" })
like image 24
Erik Funkenbusch Avatar answered Dec 10 '22 02:12

Erik Funkenbusch


I believe you want to use an ActionLink instead. This will allow you to add any attributes you want.

@Html.ActionLink("BAR", "Index", "Home", new { page }, new { @class = "FOO" })

output:

<a href="home/index?page=2" class="FOO">BAR</a>

or you can do it "manually"

<a href="@Url.Action("Index", "Home", new { page })" class="FOO">BAR</a>
like image 181
Erik Philips Avatar answered Dec 10 '22 01:12

Erik Philips