How to work with Action Link when using CSS

2019-03-03 08:31发布

<li class="rtsLI" id="Summary"><a href="javascript:void(0);" onclick="javascript:rtsXXX.OnClientTabSelected(this‌​, 0);" class="rtsLink"><span class="rtsTxt">Test</span></a></li> 

Above I am replacing with following actionlink:

<li class="rtsLI" >@Html.ActionLink("test1", "Index", new { Area = "Area1", Controller = "controller1" }, new { @class = "rtsLink rtsTxt"})</li> "

At first css is working fine. But when using Actionlink, css not working. Thanks

3条回答
孤傲高冷的网名
2楼-- · 2019-03-03 09:06

The standard ActionLink helper always HTML encodes the link text. This means that you cannot use it if you want to render HTML inside. You have 3 possibilities:

  1. Modify your CSS so that you don't need a span inside the link and so that the rtsTxt class could directly be applied to the link
  2. Write a custom ActionLink helper that doesn't HTML encode the text and which would allow you to generate the same markup:

    public static class ActionLinkExtensions
    {
        public static IHtmlString ActionLinkUnencoded(
            this HtmlHelper htmlHelper, 
            string linkText, 
            string actionName, 
            object routeValues, 
            object htmlAttributes
        )
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
            var link = new TagBuilder("a");
            link.MergeAttributes(new RouteValueDictionary(htmlAttributes));
            link.Attributes["href"] = urlHelper.Action(actionName, routeValues);
            link.InnerHtml = linkText;
            return new HtmlString(link.ToString());
        }
    }
    

    and then:

    <li>
        @Html.ActionLinkUnencoded(
            "<span class=\"rtsTxt\">User Security</span>", 
            "index", 
            new { area = "Tools", controller = "UserSecurity" }, 
            new { @class = "rtsLink" }
        )
    </li>
    
  3. Use the Url.Action helper:

    <li class="rtsLI">
        <a href="@Url.Action("index", new { area = "Tools", controller = "UserSecurity" })" class="rtsLink">
            <span class="rtsTxt">User Security</span>
        </a>
    </li>
    
查看更多
在下西门庆
3楼-- · 2019-03-03 09:17

Best option will be to use @Url.Action extension method

<li class="rtsLI" id="Summary"><a href="@Url.Action("Index", new { Area = "Tools", Controller = "UserSecurity" })" class="rtsLink"><span class="rtsTxt">User Security</span></a></li>
查看更多
女痞
4楼-- · 2019-03-03 09:20

Write code this way:

<li class="rtsLI" >@Html.ActionLink("<span class='rtsTxt'>User Security</span>", "Index", new { Area = "Tools", Controller = "UserSecurity" }, new { @class = "rtsLink"})</li>`
查看更多
登录 后发表回答