net mvc link asp c# .net asp.net-mvc actionlink

c# - asp - mvc a href action link



Colocando HTML dentro de Html.ActionLink(), además de No Link Text? (11)

Aquí hay una expansión súper de la respuesta de @tvanfosson. Me inspiré y decidí hacerlo más genérico.

public static MvcHtmlString NestedActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues = null, object htmlAttributes = null, RouteValueDictionary childElements = null) { var htmlAttributesDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); if (childElements != null) { var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext); var anchorTag = new TagBuilder("a"); anchorTag.MergeAttribute("href", routeValues == null ? urlHelper.Action(actionName, controllerName) : urlHelper.Action(actionName, controllerName, routeValues)); anchorTag.MergeAttributes(htmlAttributesDictionary); TagBuilder childTag = null; if (childElements != null) { foreach (var childElement in childElements) { childTag = new TagBuilder(childElement.Key.Split(''|'')[0]); object elementAttributes; childElements.TryGetValue(childElement.Key, out elementAttributes); var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(elementAttributes); foreach (var attribute in attributes) { switch (attribute.Key) { case "@class": childTag.AddCssClass(attribute.Value.ToString()); break; case "InnerText": childTag.SetInnerText(attribute.Value.ToString()); break; default: childTag.MergeAttribute(attribute.Key, attribute.Value.ToString()); break; } } childTag.ToString(TagRenderMode.SelfClosing); if (childTag != null) anchorTag.InnerHtml += childTag.ToString(); } } return MvcHtmlString.Create(anchorTag.ToString(TagRenderMode.Normal)); } else { return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributesDictionary); } }

Tengo dos preguntas:

  1. Me pregunto cómo puedo mostrar ningún texto de enlace cuando uso Html.ActionLink() en una vista de MVC (en realidad, esto es Site.Master ).

No hay una versión sobrecargada que no permita el texto del enlace, y cuando intento pasar solo una string blanco, el compilador me dice que necesita una cadena que no esté vacía.

¿Cómo puedo arreglar esto?

  1. Necesito poner etiquetas <span> dentro de la etiqueta de anclaje, pero no está funcionando con Html.ActionLink(); . Me gustaría ver el siguiente resultado:

    Texto de extensión

¿Cómo puedo poner etiquetas dentro de la etiqueta de anclaje en ASP.NET MVC?


En lugar de usar Html.ActionLink puedes renderizar una URL a través de Url.Action

<a href="<%= Url.Action("Index", "Home") %>"><span>Text</span></a> <a href="@Url.Action("Index", "Home")"><span>Text</span></a>

Y para hacer una url en blanco, podrías tener

<a href="<%= Url.Action("Index", "Home") %>"></a> <a href="@Url.Action("Index", "Home")"></a>


Es muy sencillo.

Si quieres tener algo así como un icono de glyphicon y luego "Wish List",

<span class="glyphicon-heart"></span> @Html.ActionLink("Wish List (0)", "Index", "Home")


Esta es una solución (baja y sucia) en caso de que necesite usar ajax o alguna característica que no pueda usar al hacer el enlace manualmente (usando la etiqueta):

<%= Html.ActionLink("LinkTextToken", "ActionName", "ControllerName").ToHtmlString().Replace("LinkTextToken", "Refresh <span class=''large sprite refresh''></span>")%>

Puede usar cualquier texto en lugar de ''LinkTextToken'', está allí para ser reemplazado, solo es importante que no ocurra en ningún otro lugar dentro de actionlink.


Esto siempre me ha funcionado bien. No es sucio y muy limpio.

<a href="@Url.Action("Index", "Home")"><span>Text</span></a>


Intente a continuación el código que puede ayudarlo.

@Html.ActionLink(" SignIn", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" ,**@class="glyphicon glyphicon-log-in"** })


Mi solución usando componentes bootstrap:

<a class="btn btn-primary" href="@Url.Action("resetpassword", "Account")"> <span class="glyphicon glyphicon-user"></span> Reset Password </a>


Pensé que esto podría ser útil al usar bootstrap y algunos glypicons:

<a class="btn btn-primary" href="<%: Url.Action("Download File", "Download", new { id = msg.Id, distributorId = msg.DistributorId }) %>"> Download <span class="glyphicon glyphicon-paperclip"></span> </a>

Esto mostrará una etiqueta A, con un enlace a un controlador, con un bonito icono de clip para representar un enlace de descarga, y la salida html se mantiene limpia.


Simplemente use Url.Action lugar de Html.ActionLink :

<li id="home_nav"><a href="<%= Url.Action("ActionName") %>"><span>Span text</span></a></li>


Terminé con un método de extensión personalizado. Vale la pena señalar que, al tratar de colocar HTML dentro de un objeto Anchor, el texto del enlace puede ser a la izquierda o a la derecha del HTML interno. Por este motivo, opté por proporcionar parámetros para HTML interno izquierdo y derecho; el texto del enlace está en el medio. Tanto el HTML interno izquierdo como el derecho son opcionales.

Método de extensión ActionLinkInnerHtml:

public static MvcHtmlString ActionLinkInnerHtml(this HtmlHelper helper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues = null, IDictionary<string, object> 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; }

Ejemplo de uso:

Aquí hay un ejemplo de uso. Para este ejemplo, solo quería el html interno en el lado derecho del texto del enlace ...

@Html.ActionLinkInnerHtml( linkText: "Hello World" , actionName: "SomethingOtherThanIndex" , controllerName: "SomethingOtherThanHome" , rightInnerHtml: "<span class=/"caret/" />" )

Resultados:

esto da como resultado el siguiente HTML ...

<a href="/SomethingOtherThanHome/SomethingOtherThanIndex">Hello World<span class="caret" /></a>


Una extensión HtmlHelper personalizada es otra opción. Nota : ParameterDictionary es mi propio tipo. Podrías sustituir un RouteValueDictionary pero tendrías que construirlo de manera diferente.

public static string ActionLinkSpan( this HtmlHelper helper, string linkText, string actionName, string controllerName, object htmlAttributes ) { TagBuilder spanBuilder = new TagBuilder( "span" ); spanBuilder.InnerHtml = linkText; return BuildNestedAnchor( spanBuilder.ToString(), string.Format( "/{0}/{1}", controllerName, actionName ), htmlAttributes ); } private static string BuildNestedAnchor( string innerHtml, string url, object htmlAttributes ) { TagBuilder anchorBuilder = new TagBuilder( "a" ); anchorBuilder.Attributes.Add( "href", url ); anchorBuilder.MergeAttributes( new ParameterDictionary( htmlAttributes ) ); anchorBuilder.InnerHtml = innerHtml; return anchorBuilder.ToString(); }