如何在 ASP.NET MVC 中将 CSS 类应用到 Html.ActionLink?

我正在构建一个 ASP.NET MVC应用程序,使用的是 VB.NET,我正在尝试使用以下代码将 css 类应用到 Html.ActionLink:

<%=Html.ActionLink("Home", "Index", "Home", new {@class = "tab" })%>

但是当我运行代码时,我会收到以下错误:

编译器错误消息: BC30988: 预期输入或“ With”。

我对 车祸还是个新手,真的不太清楚我在做什么,所以我看不出有什么问题,因为我使用的代码是基于其他地方的一个例子。

202153 次浏览

It is:

<%=Html.ActionLink("Home", "Index", MyRouteValObj, new with {.class = "tab" })%>

In VB.net you set an anonymous type using

new with {.class = "tab" }

and, as other point out, your third parameter should be an object (could be an anonymous type, also).

In VB.NET

<%=Html.ActionLink("Contact Us", "ContactUs", "Home", Nothing, New With {.class = "link"})%>

This will assign css class "link" to the Contact Us.

This will generate following HTML :

<a class="link" href="www.domain.com/Home/ContactUs">Contact Us</a>

This syntax worked for me in MVC 3 with Razor:

@Html.ActionLink("Delete", "DeleteList", "List", new { ID = item.ID, ListID = item.id }, new {@class= "delete"})

@ewomack has a great answer for C#, unless you don't need extra object values. In my case, I ended up using something similar to:

@Html.ActionLink("Delete", "DeleteList", "List", new object { },
new { @class = "delete"})

In C# it also works with a null as the 4th parameter.

@Html.ActionLink( "Front Page", "Index", "Home", null, new { @class = "MenuButtons" })

This works for MVC 5

@Html.ActionLink("LinkText", "ActionName", new { id = item.id }, new { @class = "btn btn-success" })

This will work , tested in MVC core 6

  • Good code readability

  • it allow you set other html attributes , eg i use target attribute to open new tab

  • it allow you set class value , eg i use bootstrap convert hyperlink to button

  • it allow you apply custom inline style

         @Html.ActionLink(
    linkText: "Button\Hyperlink Label",
    actionName: "Index",
    controllerName: "Home",
    routeValues: new { Id = @item.ToString() },
    htmlAttributes: new { target = "_blank",@class="btn" , @style="background-color:lightblue;margin: 10px 30px;"})