andy
andy

Reputation: 485

Using Conditional HTML Attributes in Custom ActionLink Helper MVC

I am using a custom HTML action link helper and would like to know if it's possible to implement a Condition Attribute function in the text portion of the action link helper. I have defined a CSS class to format the li element of my list. It works when I statically define it in the text portion of the Helper.

However, what I want is to something like this

@Html.MyActionLink("<li>Foo\@IsCurrentPage("Page1")\</li>",...

Is it possible to insert the function IsCurrentPage in this manner. I already tried using the HTML attributes of the helper, but it seems to apply to the when I only want to style the

  • . Should I refocus on working through the helpers HTML attributes. Or is using the function the way to do this?

    Here is the relevant code.

    Helper:

     public static IHtmlString MyActionLink(
        this HtmlHelper htmlHelper,
        string linkText,
        string action,
        string controller,
        object routeValues,
        object htmlAttributes
    )
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
            var anchor = new TagBuilder("a");
            anchor.InnerHtml = linkText;
            anchor.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
            anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
            return MvcHtmlString.Create(anchor.ToString());
        }
    
    
        }
    

    Helper Implementation:

    @Html.MyActionLink(
                    "<li>Foo</li>",
                    "MyAction",
                    "MyController",
                    null,
                    null
                    )
    

    Conditional Attribute Function:

    @functions {
    public static string CurrentPage(string page)
    {
        return HttpContext.Current.Request.Url.ToString().Contains(page) ? "active-tab" : null;
    }
    

    }

    Upvotes: 0

    Views: 386

  • Answers (1)

    andy
    andy

    Reputation: 485

    Since the HTML MyActionLink helper defined the text passed in as a string, I was just dealing with strings. String can be concatenated together to by using the "+" sign between items to be joined. The function I using to determine which class to use in the li tag is defined in the Razor notation and could be injected between the two parts of the strings I created.

    Upvotes: 0

    Related Questions