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" })
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" })
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With