pass mvc icon asp.net-mvc routing

icon - Imagen equivalente de ActionLink en ASP.NET MVC



url action post (14)

Tomé las respuestas anteriores e hice un poco de una extensión de contenedor:

public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string src, string altText, UrlHelper url, string actionName, string controllerName) { return ActionImageLink(helper, src, altText, url, actionName, controllerName, null, null); } public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string src, string altText, UrlHelper url, string actionName, string controllerName, Dictionary<string, string> linkAttributes, Dictionary<string, string> imageAttributes) { return ActionImageLink(helper, src, altText, url, actionName, controllerName, null, linkAttributes, imageAttributes); } public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string src, string altText, UrlHelper url, string actionName, string controllerName, dynamic routeValues, Dictionary<string, string> linkAttributes, Dictionary<string, string> imageAttributes) { var linkBuilder = new TagBuilder("a"); linkBuilder.MergeAttribute("href", routeValues == null ? url.Action(actionName, controllerName) : url.Action(actionName, controllerName, routeValues)); var imageBuilder = new TagBuilder("img"); imageBuilder.MergeAttribute("src", url.Content(src)); imageBuilder.MergeAttribute("alt", altText); if (linkAttributes != null) { foreach (KeyValuePair<string, string> attribute in linkAttributes) { if (!string.IsNullOrWhiteSpace(attribute.Key) && !string.IsNullOrWhiteSpace(attribute.Value)) { linkBuilder.MergeAttribute(attribute.Key, attribute.Value); } } } if (imageAttributes != null) { foreach (KeyValuePair<string, string> attribute in imageAttributes) { if (!string.IsNullOrWhiteSpace(attribute.Key) && !string.IsNullOrWhiteSpace(attribute.Value)) { imageBuilder.MergeAttribute(attribute.Key, attribute.Value); } } } linkBuilder.InnerHtml = MvcHtmlString.Create(imageBuilder.ToString(TagRenderMode.SelfClosing)).ToString(); return MvcHtmlString.Create(linkBuilder.ToString()); }

me ha hecho las cosas más fáciles de todos modos, espero que ayude a alguien más.

En ASP.NET MVC, ¿hay un equivalente del ayudante Html.ActionLink para las etiquetas Img?

Tengo una acción de controlador que genera un JPEG generado dinámicamente y quería usar las mismas expresiones Lambda para vincularme a él como lo hago HREF usando ActionLink.

Alternativamente, un ayudante que simplemente da la URL a una ruta (nuevamente especificada usando Lambdas) también sería aceptable.

EDITAR : Originalmente había especificado que estaba usando Vista previa 5, sin embargo, veo que se ha lanzado una versión beta. Así que, en general, el número de versión era una información innecesaria, ya que podría estar actualizando pronto :-)


Url.Action () obtendrá la URL vacía para la mayoría de las sobrecargas de Html.ActionLink, pero creo que la funcionalidad URL-from-lambda solo está disponible a través de Html.ActionLink hasta el momento. Con suerte, agregarán una sobrecarga similar a Url.Action en algún momento.


En ASP.NET MVC Beta, puede usar el método Html.BuildUrlFromExpression en el ensamblaje Futures (que no está incluido en la instalación predeterminada de ASP.NET MVC, pero está disponible desde CodePlex ) para crear un vínculo alrededor de una imagen, o cualquier HTML - usando la sintaxis ActionLink de estilo lambda, así:

<a href="<%=Html.BuildUrlFromExpression<MyController>(c => c.MyAction())%>"> <%=Html.Image("~/Content/MyImage.gif")%> </a>

Para mantener sus enlaces de imagen sin márgenes, deberá agregar una regla de CSS como esta:

img { border: none; }


Usé una solución alternativa para colocar un marcador en lugar de texto para ActionLink y luego reemplazarlo con mi código de imagen. Algo como esto:

<%= Html.ActionLink("__IMAGE_PLACEHOLDER__", "Products").Replace("__IMAGE_PLACEHOLDER__", "<img src=/"" + myImgUrl + "/" />")%>

No es la solución más elegante, pero funciona.


Esta pregunta es más antigua, y acabo de comenzar recientemente con ASP.NET MVC cuando el RC ya estaba fuera, pero para aquellos que encuentran esta pregunta más tarde como yo, esto podría ser interesante:

Al menos en el RC se puede usar Url.Action () también con tipos anónimos, el resultado parece mucho mejor que las sugerencias anteriores, supongo:

<a href="<%= Url.RouteUrl("MyRoute", new { param1 = "bla", param2 = 5 }) %>"> put in <span>whatever</span> you want, also <img src="a.gif" alt="images" />. </a>

También hay muchas otras sobrecargas para RouteUrl, por supuesto.



¿Url.Content () es lo que estás buscando?

Dale algo como Url.Content ("~ / ruta / a / algo.jpg") lo convertirá en la ruta adecuada en función de la raíz de la aplicación.

-Josh


Puedes usar el método URL.Action

<a href="<%= Url.Action("Create") %>"><img src="../../Content/Images/add_48.png" /></a>


Es bastante simple de lograr en MVC 2. He creado mi propio método de extensión muy simple para soportar expresiones Lambda para el ayudante Url.Action. Requiere que haga referencia a MVC 2 Futures.
Aquí está el código:

using System; using System.Linq.Expressions; using System.Web.Mvc; using System.Web.Routing; using ExpressionHelperInternal=Microsoft.Web.Mvc.Internal.ExpressionHelper; namespace Bnv.Bssi.Web.Infrastructure.Helpers { public static class UrlExtensions { public static string Action<TController>(this UrlHelper helper, Expression<Action<TController>> action) where TController : Controller { RouteValueDictionary routeValuesFromExpression = ExpressionHelperInternal.GetRouteValuesFromExpression<TController>(action); return helper.Action(routeValuesFromExpression["action"].ToString(), routeValuesFromExpression); } } }

Así es como lo usas:

<img src="<%= Url.Action<YourController>(c => c.YourActionMethod(param1, param2)); %>" />


Traté de poner el resultado de Html.Image en mi ayuda Html.ImageLink .

@(new HtmlString(Html.ActionLink(Html.Image("image.gif").ToString(), "myAction", "MyController").ToString().Replace("&lt;", "<").Replace("&gt;", ">")))

El problema para mí es que el nombre de ActionLink está codificado, así que tengo & lt en lugar de <.

Acabo de eliminar esta codificación y el resultado funciona para mí. (¿Hay una mejor manera de hacerlo en lugar de usar replace?)


En MVC3, su enlace se vería así:

<a href="@Url.Action("Create")"><img src="../../Content/Images/add_48.png" /></a>


Sé que mi publicación es demasiado tarde, pero quiero compartir :)

Agregué un nuevo método de extensión como este:

public static class ImageExtensions { public static MvcHtmlString ImageLink(this HtmlHelper htmlHelper, string imgSrc, string additionalText = null, string actionName = null, string controllerName = null, object routeValues = null, object linkHtmlAttributes = null, object imgHtmlAttributes = null) { var urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url; var url = "#"; if (!string.IsNullOrEmpty(actionName)) url = urlHelper.Action(actionName, controllerName, routeValues); var imglink = new TagBuilder("a"); imglink.MergeAttribute("href", url); imglink.InnerHtml = htmlHelper.Image(imgSrc, imgHtmlAttributes) + " " + additionalText; linkHtmlAttributes = new RouteValueDictionary(linkHtmlAttributes); imglink.MergeAttributes((IDictionary<string, object>)linkHtmlAttributes, true); return MvcHtmlString.Create(imglink.ToString()); } public static MvcHtmlString Image(this HtmlHelper htmlHelper, string imgSrc, object imgHtmlAttributes = null) { var imgTag = new TagBuilder("img"); imgTag.MergeAttribute("src", imgSrc); if (imgHtmlAttributes != null) { imgHtmlAttributes = new RouteValueDictionary(imgHtmlAttributes); imgTag.MergeAttributes((IDictionary<string, object>)imgHtmlAttributes, true); } return MvcHtmlString.Create(imgTag.ToString()); } }

Espero que esto haya ayudado.


Agregando a las otras publicaciones: en mi caso (asp.net mvc 3) Quería un enlace de imagen para actuar como selector de idioma, así que terminé con:

public static MvcHtmlString ImageLink(this HtmlHelper htmlHelper, string imgSrc, string cultureName, object htmlAttributes, object imgHtmlAttributes, string languageRouteName = "lang", bool strictSelected = false) { UrlHelper urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url; TagBuilder imgTag = new TagBuilder("img"); imgTag.MergeAttribute("src", imgSrc); imgTag.MergeAttributes((IDictionary<string, string>)imgHtmlAttributes, true); var language = htmlHelper.LanguageUrl(cultureName, languageRouteName, strictSelected); string url = language.Url; TagBuilder imglink = new TagBuilder("a"); imglink.MergeAttribute("href", url); imglink.InnerHtml = imgTag.ToString(); imglink.MergeAttributes((IDictionary<string, string>)htmlAttributes, true); //if the current page already contains the language parameter make sure the corresponding html element is marked string currentLanguage = htmlHelper.ViewContext.RouteData.GetRequiredString("lang"); if (cultureName.Equals(currentLanguage, StringComparison.InvariantCultureIgnoreCase)) { imglink.AddCssClass("selectedLanguage"); } return new MvcHtmlString(imglink.ToString()); }

El soporte de internalización se realizó a través de una ruta de idioma, fuente original aquí .


Buenas soluciones aquí, pero ¿y si quieres tener más que solo una imagen en el enlace de acción? Así es como lo hago:

@using (Html.BeginForm("Action", "Controler", ajaxOptions)) { <button type="submit"> <img src="image.png" /> </button> }

El inconveniente es que todavía tengo que darle un toque de estilo al botón-elemento, pero puedes poner todo el html que quieras allí.

Y también funciona con el asistente de Ajax: https://.com/a/19302438/961139