ajax asp.net-mvc html.actionlink

ASP.NET MVC Ajax.ActionLink con imagen



asp.net-mvc html.actionlink (20)

.li_inbox {background: url (inbox.png) no-repeat; relleno a la izquierda: 40px; / imagen de fondo wight 40px /}

<li class="li_inbox" > @Ajax.ActionLink("Inbox", "inbox","Home", new { }, new AjaxOptions { UpdateTargetId = "MainContent", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" })

¿Hay alguna forma de que una imagen actúe como un enlace de acción ajax? Solo puedo hacer que funcione usando texto. ¡Gracias por tu ayuda!


Solución general: incluye cualquier Navaja que quieras dentro del enlace de acción

Hay una solución mucho mejor usando delegados de plantillas Razor, que permite insertar cualquier código Razor dentro del enlace de acción de una manera muy natural. Entonces puedes agregar una imagen o cualquier otro código.

Este es el método de extensión:

public static IHtmlString ActionLink<T>(this AjaxHelper ajaxHelper, T item, Func<T,HelperResult> template, string action, string controller, object routeValues, AjaxOptions options) { string rawContent = template(item).ToHtmlString(); MvcHtmlString a = ajaxHelper.ActionLink("$$$", action, controller, routeValues, options); return MvcHtmlString.Create(a.ToString().Replace("$$$", rawContent)); }

Y así es como se puede usar:

@Ajax.ActionLink(car, @<div> <h1>@car.Maker</h1> <p>@car.Description</p> <p>Price: @string.Format("{0:C}",car.Price)</p> </div>, ...

Esto permite escribir Razor con intellisense, y usar cualquier objeto que desee para la plantilla (el ViewModel, o cualquier otro objeto, como el auto de mi muestra). Y puede usar cualquier ayuda dentro de la plantilla para anidar imágenes o el elemento que desee.

Nota para los usuarios de Resharper

Si está utilizando R # en su proyecto, puede agregar anotaciones R # para mejorar Intellisense:

public static IHtmlString ActionLink<T>(this AjaxHelper ajaxHelper, T item, Func<T, HelperResult> template, [AspMvcAction] string action, [AspMvcController] string controller, object routeValues, AjaxOptions options)


Actualización para MVC3 con Templated Razor Delegates se basa en T4Mvc , pero aporta mucho poder.

Basado en varias otras respuestas en esta página.

public static HelperResult WrapInActionLink(this AjaxHelper helper,ActionResult result, Func<object,HelperResult> template,AjaxOptions options) { var link=helper.ActionLink("[replaceme]",result,options); var asString=link.ToString(); var replaced=asString.Replace("[replaceme]",template(null).ToString()); return new HelperResult(writer => { writer.Write(replaced); }); }

Permite:

@Ajax.WrapInActionLink(MVC.Deal.Details(deal.ID.Value),@<img alt=''Edit deal details'' src=''@Links.Content.Images.edit_16_gif''/>, new AjaxOptions() { UpdateTargetId="indexDetails" })


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 (Ajax.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í.


Cada respuesta es buena, pero encontré la más fácil:

@Html.ActionLink( " ", "Index", "Countries", null, new { style = "background: url(''../../Content/Images/icon.png'') no-repeat center right;display:block; height:24px; width:24px;margin-top:-2px;text-decoration:none;" } )

Tenga en cuenta que está utilizando un espacio en blanco ("") para el texto del enlace. No funcionará con un texto vacío.


Consulte la versión 7 del Tutorial de Contact Manager en http://asp.net/mvc . Stephen Walther tiene un ejemplo de crear un Ajax.ActionLink que es una imagen.


De Stephen Walthe, de su proyecto de administrador de contactos

public static class ImageActionLinkHelper { public static string ImageActionLink(this AjaxHelper helper, string imageUrl, string altText, string actionName, object routeValues, AjaxOptions ajaxOptions) { var builder = new TagBuilder("img"); builder.MergeAttribute("src", imageUrl); builder.MergeAttribute("alt", altText); var link = helper.ActionLink("[replaceme]", actionName, routeValues, ajaxOptions); return link.Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing)); } }

Ahora puede escribir su archivo aspx:

<%= Ajax.ImageActionLink("../../Content/Delete.png", "Delete", "Delete", new { id = item.Id }, new AjaxOptions { Confirm = "Delete contact?", HttpMethod = "Delete", UpdateTargetId = "divContactList" })%>


Esta es la solución más fácil que he encontrado:

<%= Ajax.ActionLink("[replacethis]", ...).Replace("[replacethis]", "<img src=/"/images/test.gif/" ... />" %>

La llamada Reemplazar () se utiliza para insertar la etiqueta img en el enlace de acción. Solo necesita usar el texto "[replaceme]" (o cualquier otro texto seguro) como marcador de posición temporal para crear el enlace.


He encontrado que de lejos la mejor solución para esto es usar la etiqueta de entrada con type = "image"

@using (Ajax.BeginForm( "LoadTest","Home" , new System.Web.Mvc.Ajax.AjaxOptions { UpdateTargetId = "[insert your target tag''s id here]" })) { <input type="image" class="[css style class here]" src="[insert image link here]"> }

Es fácil y rápido.

Lo he usado en combinación con otras bibliotecas de controles que interfieren con AjaxOptions, así que tiendo a escribir todo el System.Web.Mvc.Ajax.AjaxOptions en caso de que termine probando un conjunto diferente en el futuro.

NOTA: He notado que esto parece tener problemas dentro de MVC3 (algo que ver con type = "image"), pero funciona para MVC 4


La primera solución es usar un método estático auxiliar DecodeLinkContent como el siguiente:

DecodeLinkContent(Html.ActionLink<Home>(c => c.Delete(item.ID), "<span class=/"redC/">X</span>",new { Class = "none left"}))

DecodeLinkContent tiene que encontrar primero ''>'' y último ''<'' y tiene que reemplazar el contenido con HttpUtility.Decode (contenido).

Esta solución es un truco, pero creo que es la más fácil.


La respuesta corta es que no es posible. Sus opciones son escribir su propio método de extensión para tener un ImageActionLink, no demasiado difícil de hacer. O agregue un atributo a actionLink y reemplace innerhtml con la etiqueta de imagen.


Otra solución es crear su propio método de extensión:

ActionLink<TController>(this HtmlHelper helper, Expression<Action<TController>> action, string linkText, object htmlAttributes, LinkOptions options)

y como el último parámetro es la enumeración LinkOptions

[Flags] public enum LinkOptions { PlainContent = 0, EncodeContent = 1, }

y luego puedes usarlo de la siguiente manera:

Html.ActionLink<Car>( c => c.Delete(item.ID), "<span class=/"redC/">X</span>", new { Class = "none left" }, LinkOptions.PlainContent)

Publicaré una descripción completa de esta solución en mi blog: http://fknet.wordpress.com/


Otros no funcionaron para mí ya que .ToHtmlString () escupió una cadena en MVC 4.

A continuación, se pasa una identificación al control de edición y se muestra una imagen de edición en lugar del espacio de texto:

@MvcHtmlString.Create(Ajax.ActionLink("Spag", "Edit", new { id = item.x0101EmployeeID }, new AjaxOptions() { UpdateTargetId = "selectDiv", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" }).ToHtmlString().Replace("Spag", "<img src=/"" + Url.Content("../../Images/edit.png") + "/" />"))


Prueba esto

@Html.Raw(HttpUtility.HtmlDecode(Ajax.ActionLink( "<img src=/"/images/sjt.jpg/" title=/"上一月/" border=/"0/" alt=/"上一月/" />", "CalendarPartial", new { strThisDate = Model.dtCurrentDate.AddMonths(-1).ToString("yyyy-MM-dd") }, new AjaxOptions { @UpdateTargetId = "calendar" }).ToString()))


Todas son soluciones muy agradables, pero si no te gusta tener un replace en tu solución puedes probar esto:

{ var url = new UrlHelper(helper.ViewContext.RequestContext); // build the <img> tag var imgBuilder = new TagBuilder("img"); imgBuilder.MergeAttribute("src", url.Content(imageUrl)); imgBuilder.MergeAttribute("alt", altText); string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing); //build the <a> tag var anchorBuilder = new TagBuilder("a"); anchorBuilder.MergeAttribute("href", url.Action(actionName, controller, routeValues)); anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside anchorBuilder.MergeAttributes<string, object>(ajaxOptions.ToUnobtrusiveHtmlAttributes()); string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal); return MvcHtmlString.Create(anchorHtml); }

Además, en mi caso, si no utilizo url.Content(imageUrl) , la imagen no se muestra.


Usa esta extensión para generar un enlace ajax con glifyphicon:

/// <summary> /// Create an Ajax.ActionLink with an associated glyphicon /// </summary> /// <param name="ajaxHelper"></param> /// <param name="linkText"></param> /// <param name="actionName"></param> /// <param name="controllerName"></param> /// <param name="glyphicon"></param> /// <param name="ajaxOptions"></param> /// <param name="routeValues"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcHtmlString ImageActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, string glyphicon, AjaxOptions ajaxOptions, RouteValueDictionary routeValues = null, object htmlAttributes = null) { //Example of result: //<a id="btnShow" href="/Customers/ShowArtworks?customerId=1" data-ajax-update="#pnlArtworks" data-ajax-success="jsSuccess" //data-ajax-mode="replace" data-ajax-method="POST" data-ajax-failure="jsFailure" data-ajax-confirm="confirm" data-ajax-complete="jsComplete" //data-ajax-begin="jsBegin" data-ajax="true"> // <i class="glyphicon glyphicon-pencil"></i> // <span>Edit</span> //</a> var builderI = new TagBuilder("i"); builderI.MergeAttribute("class", "glyphicon " + glyphicon); string iTag = builderI.ToString(TagRenderMode.Normal); string spanTag = ""; if (!string.IsNullOrEmpty(linkText)) { var builderSpan = new TagBuilder("span") { InnerHtml = " " + linkText }; spanTag = builderSpan.ToString(TagRenderMode.Normal); } //Create the "a" tag that wraps var builderA = new TagBuilder("a"); var requestContext = HttpContext.Current.Request.RequestContext; var uh = new UrlHelper(requestContext); builderA.MergeAttribute("href", uh.Action(actionName, controllerName, routeValues)); builderA.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); builderA.MergeAttributes((ajaxOptions).ToUnobtrusiveHtmlAttributes()); builderA.InnerHtml = iTag + spanTag; return new MvcHtmlString(builderA.ToString(TagRenderMode.Normal)); }


Usar atributos de datos Html

<a data-ajax="true" data-ajax-begin="..." data-ajax-success="..." href="@Url.Action("Delete")"> <i class="halflings-icon remove"></i> </a>

Reemplace la

<i class="halflings-icon remove"></i>

con tu propia imagen


Esta es una actualización de Razor / MVC 3 (y posterior) a la respuesta de Black Horus:

using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; public static class ImageActionLinkHelper { public static IHtmlString ImageActionLink(this AjaxHelper helper, string imageUrl, string altText, string actionName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes = null) { var builder = new TagBuilder("img"); builder.MergeAttribute("src", imageUrl); builder.MergeAttribute("alt", altText); builder.MergeAttributes(new RouteValueDictionary(htmlAttributes)); var link = helper.ActionLink("[replaceme]", actionName, routeValues, ajaxOptions).ToHtmlString(); return MvcHtmlString.Create(link.Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing))); } }

Ahora puede escribir su archivo .cshtml:

@Ajax.ImageActionLink("../../Content/Delete.png", "Delete", "Delete", new { id = item.Id }, new AjaxOptions { Confirm = "Delete contact?", HttpMethod = "Delete", UpdateTargetId = "divContactList" })

31 de octubre de 2013: actualizado con un parámetro adicional para permitir el establecimiento de atributos HTML adicionales para el elemento de la imagen. Uso:

@Ajax.ImageActionLink("../../Content/Delete.png", "Delete", "Delete", new { id = item.Id }, new AjaxOptions { Confirm = "Delete contact?", HttpMethod = "Delete", UpdateTargetId = "divContactList" }, new{ style="border: none;" })


MVC3, Html.ActionImageLink y Ajax.ActionImageLink

Gracias a todas las demás respuestas por ayudarme con esto.

public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string imageUrl, string altText, string actionName, string controller, object routeValues) { var builder = new TagBuilder("img"); builder.MergeAttribute("src", imageUrl); builder.MergeAttribute("alt", altText); var link = helper.ActionLink("[replaceme]", actionName, controller, routeValues); return new MvcHtmlString(link.ToHtmlString().Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing))); } public static MvcHtmlString ActionImageLink(this AjaxHelper helper, string imageUrl, string altText, string actionName, string controller, object routeValues, AjaxOptions ajaxOptions) { var builder = new TagBuilder("img"); builder.MergeAttribute("src", imageUrl); builder.MergeAttribute("alt", altText); var link = helper.ActionLink("[replaceme]", actionName, controller, routeValues, ajaxOptions); return new MvcHtmlString(link.ToHtmlString().Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing))); }


actionName+"/"+routeValues Proje/ControlName/ActionName/Id using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; namespace MithatCanMvc.AjaxHelpers { public static class ImageActionLinkHelper { public static IHtmlString ImageActionLink(this AjaxHelper helper, string imageUrl, string altText, string actionName, string routeValues, AjaxOptions ajaxOptions) { var builder = new TagBuilder("img"); builder.MergeAttribute("src", imageUrl); builder.MergeAttribute("alt", altText); var link = helper.ActionLink("[replaceme]", actionName+"/"+routeValues, ajaxOptions).ToHtmlString(); return MvcHtmlString.Create(link.Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing))); } } }