4

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" })
4
  • something like this in the new: @Url.Action("Index", "Home", new { page, className="foo" }) Commented May 14, 2012 at 18:41
  • 2
    @MilkyWayJoe I think its new { @class= '...' } no? Commented May 14, 2012 at 18:41
  • @MilkyWayJoe: I think that will append &class=foo to the url. The answer below seems to be that I need to use ActionLink instead. Commented May 14, 2012 at 18:49
  • Sorry guys, I definitely need a coffee after lunch, it's NOT className as I said earlier Commented May 14, 2012 at 18:52

4 Answers 4

13

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>
Sign up to request clarification or add additional context in comments.

1 Comment

The second approach Erik mentions above (doing it "manually") is the way to go if you need to nest another tag inside the <a> tag (for instance, a <span> tag that renders an icon via a font). See Putting HTML inside Html.ActionLink(), plus No Link Text for more info.
6

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" })

Comments

1

The Url.Action helper will simply print the url not the full anchor.

Your two options are:

@Html.ActionLink("BAR", "index","home", new { @class = "FOO" })
  • note the use of the @ symbol on the class as class is a reserved keyword

and (using the Url.Action helper)

<a href="@Url.Action("Index", "Home", new { page })" class="FOO">BAR</a>

Comments

0

Here's what I do:

I have this class:

public class HtmlValues : Dictionary<string,object>
{
    public HtmlValues Class(string ClassName)
    {
        if (this.ContainsKey("class"))
        {
            ClassName = String.Format("{0} {1}", this["class"], ClassName);
            this.Remove("class");
        }
        return this.WithValue("class", ClassName);
    }
    public HtmlValues Name(string Name)
    {
        return this.WithValue("name", Name);
    }
    public HtmlValues Style(string Style)
    {
        return this.WithValue("style", Style);
    }
    public HtmlValues MaxLength(int Length)
    {
        return this.WithValue("maxlength", Length.ToString());
    }
    public HtmlValues RTL()
    {
        return this.WithValue("dir", "rtl");
    }
    public HtmlValues With(string Attribute, string Value)
    {
        return this.WithValue(Attribute, Value);
    }

    public static HtmlValues WithClass(string CssClass)
    {
        return new HtmlValues().Class(CssClass);
    }

    public HtmlValues Data(string key, string value)
    {
        return this.WithValue("data-" + key, value);
    }
}

With this extension method:

public static class Extensions
{
    public static T WithValue<T>(this T dict, string key, object value) where T : IDictionary<string, object>
    {
        dict.Add(key, value);
        return dict;
    }
}

Then my Razor looks like this:

@Html.TextBoxFor(model => model.SomeProperty, HtmlValues.WithClass("SomeClass"))

This may seem like overkill, but it is pretty nice in practice, as it lets you chain add attributes/values to the element in a nice fluent, meaningful to the reader fashion.

@Html.TextBoxFor(model => model.SomeProperty, 
    HtmlValues.WithClass("SomeClass")
              .Class("someotherClass")
              .Data("Some-Jquery-Data-Thing")
              .With("Nonstandard-Attribute","Its-Value"))

2 Comments

Looks like you sort-of rebuilt the TagBuilder.
@ErikPhilips Well look at that. It'd have been real handy to know about that way back then! Man, 9 years ago already.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.