HTML element inside an Actionlink

Asked

Viewed 676 times

5

Hi, I was wondering if it is possible to create an HTML element inside a ActionLink, for example:

To create a link in a menu with ActionLink:

@Html.ActionLink("Classificação Financeira", "Index", "ClassificacaoFinanceira")

But I need to create an element to put a figure on the menu and if I’m going to do with the tag a would look like this:

<a href="/ClassificacaoFinanceira"><i class="fa fa-bar-chart"></i> Classificação Financeira</a>

But I’d like to do it using the ActionLink, has how to do this?

  • This would not help you: <a href="@Url.Action("Index", "Classificacaofinanceira")"><i class="fa fa-bar-Chart"></i></a>

2 answers

3

The most interesting way I found to solve the problem is by creating my own extensions for the HtmlHelper. For your case, that you want to use the Fontawesome in the link, the code below solves:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MeuProjeto.Extensions
{
    public static class HtmlHelperExtensions
    {
        public static IHtmlString FontAwesomeActionLink(this HtmlHelper htmlHelper, string linkText,
            string actionName, string fontAwesomeClass, object routeValues = null, object htmlAttributes = null)
        {
            return FontAwesomeActionLink(htmlHelper, linkText, actionName, null, fontAwesomeClass, routeValues,
                htmlAttributes);
        }

        public static IHtmlString FontAwesomeActionLink(this HtmlHelper htmlHelper, string linkText,
            string actionName, string controllerName, string fontAwesomeClass, object routeValues = null, object htmlAttributes = null)
        {
            var targetUrl = UrlHelper.GenerateUrl(null, actionName, controllerName, ObjectToDictionary(routeValues), htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, true);
            return new MvcHtmlString(GenerateLink(linkText, targetUrl, fontAwesomeClass, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)));
        }

        private static string GenerateLink(string linkText,
            string targetUrl,
            string fontAwesomeClass,
            IDictionary<string, object> htmlAttributes
        )
        {
            var a = new TagBuilder("a");

            a.MergeAttributes(htmlAttributes);
            a.MergeAttribute("href", targetUrl);

            var i = new TagBuilder("i");

            i.MergeAttribute("class", "fa " + fontAwesomeClass);
            a.InnerHtml = i.ToString(TagRenderMode.Normal) + " " + linkText;

            return a.ToString(TagRenderMode.Normal);
        }
    }
}

Register the extension on web.config inside the directory Views:

<configuration>
  ...
  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System" />
        <add namespace="MeuProjeto.Extensions" /> <!-- Este -->
      </namespaces>
    </pages>
  </system.web.webPages.razor>
  ...
</configuration>

Use:

@Html.FontAwesomeActionLink("Classificação Financeira", "Indice", "ClassificacaoFinanceira", "fa fa-bar-chart")

2


You can create an extension method in your Htmlhelper and format your element the way you need it!

What an extension of Taghelper would look like:

namespace System.Web.Mvc
{
    public static class Methods
    {
        public static String ControllerName(this HtmlHelper HtmlHelper)
        {
            return HtmlHelper.ViewContext.RequestContext.RouteData.Values["controller"].ToString();
        }
        public static String ControllerName(this AjaxHelper AjaxHelper)
        {
            return AjaxHelper.ViewContext.RequestContext.RouteData.Values["controller"].ToString();
        }
        public static String ActionName(this HtmlHelper HtmlHelper)
        {
            return HtmlHelper.ViewContext.RequestContext.RouteData.Values["action"].ToString();
        }
        public static String ActionName(this AjaxHelper AjaxHelper)
        {
            return AjaxHelper.ViewContext.RequestContext.RouteData.Values["action"].ToString();
        }
        public static object GetValue<TModel, TProperty>(HtmlHelper<TModel> htmlHelper, System.Linq.Expressions.Expression<Func<TModel, TProperty>> expression)
            where TModel : class
        {
            TModel model = htmlHelper.ViewData.Model;
            if (model == null)
            {
                return default(string);
            }
            Func<TModel, TProperty> func = expression.Compile();
            return func(model);
        }
        public static IHtmlString ButtonEdit(this HtmlHelper HtmlHelper, String Description, String ActionName, String Title, params object[] routeValues)
        {
            string routes = string.Empty;
            if (routeValues.Length > 0)
            {
                foreach (object route in routeValues)
                {
                    if (routes == string.Empty)
                    {
                        routes += route;
                    }
                    else
                    {
                        routes += "/" + route;
                    }
                }
            }
            string _button = string.Format("<a href=\"{0}\" class=\"btn btn-primary\" target=\"_self\" title=\"{1}\">{2}</a>",
                string.Format("/{0}/{1}/{2}", ControllerName(HtmlHelper), ActionName, routes), Title, Description);
            return new HtmlString(_button);
        }
    }
}

Note that there are several methods for aiding and that in the method ButtonEdit and the new tag that I created.

What to call in your View:

@Html.ButtonEdit("Cadastro", "Index", "", null)
  • The problem is that fixed class there.

  • I don’t get it @Gypsy ?

  • I’m talking about this: class=\"btn btn-primary\". If I want to use another class, I can’t. Let’s assume my link is not a button.

  • 1

    @Ciganomorrisonmendez in my system was applied this CSS as default, and this is not a problem is the way I saw my system buttons and standardization. Just remembering that this is an example and should be changed to suit what it needs to do in his system! This is not a problem is a customization of mine that for you can be different.

  • Just reaffirming @Ciganomorrisonmendez my button throughout the system will be with this CSS for identification and normatives, used by the development team (It was decided that this button has this color, size and style).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.