Putting HTML inside Html.ActionLink(), plus No Link Text?

后端 未结 11 1814
忘了有多久
忘了有多久 2020-11-28 01:54

I have two questions:

  1. I\'m wondering how I can display no link text when using Html.ActionLink() in an MVC view (actually, this is Site.Mast
11条回答
  •  醉梦人生
    2020-11-28 02:21

    I ended up with a custom extension method. Its worth noting, when trying to place HTML inside of an Anchor object, the link text can be either to the left, or to the right of the inner HTML. For this reason, I opted to provide parameters for left and right inner HTML - the link text is in the middle. Both left and right inner HTML are optional.

    Extension Method ActionLinkInnerHtml:

        public static MvcHtmlString ActionLinkInnerHtml(this HtmlHelper helper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues = null, IDictionary htmlAttributes = null, string leftInnerHtml = null, string rightInnerHtml = null)
        {
            // CONSTRUCT THE URL
            var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
            var url = urlHelper.Action(actionName: actionName, controllerName: controllerName, routeValues: routeValues);
    
            // CREATE AN ANCHOR TAG BUILDER
            var builder = new TagBuilder("a");
            builder.InnerHtml = string.Format("{0}{1}{2}", leftInnerHtml, linkText, rightInnerHtml);
            builder.MergeAttribute(key: "href", value: url);
    
            // ADD HTML ATTRIBUTES
            builder.MergeAttributes(htmlAttributes, replaceExisting: true);
    
            // BUILD THE STRING AND RETURN IT
            var mvcHtmlString = MvcHtmlString.Create(builder.ToString());
            return mvcHtmlString;
        }
    

    Example of Usage:

    Here is an example of usage. For this example I only wanted the inner html on the right side of the link text...

    @Html.ActionLinkInnerHtml(
        linkText: "Hello World"
            , actionName: "SomethingOtherThanIndex"
            , controllerName: "SomethingOtherThanHome"
            , rightInnerHtml: ""
            )
    

    Results:

    this results in the following HTML...

    Hello World
    

提交回复
热议问题