73

画像をajaxアクションリンクとして機能させる方法はありますか? テキストを使用してのみ機能させることができます。ご協力いただきありがとうございます!

4

21 に答える 21

67

Stephen Walthe 氏のContact Manager プロジェクトより

 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));
    }

}

aspx ファイルに次のように入力できます。

<%= Ajax.ImageActionLink("../../Content/Delete.png", "Delete", "Delete", new { id = item.Id }, new AjaxOptions { Confirm = "Delete contact?", HttpMethod = "Delete", UpdateTargetId = "divContactList" })%> 
于 2009-11-01T19:25:35.320 に答える
35

私が見つけた最も簡単な解決策は次のとおりです。

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

Replace() 呼び出しは、 imgタグをアクション リンクにプッシュするために使用されます。リンクを作成するための一時的なプレースホルダーとして、"[replaceme]" テキスト (またはその他の安全なテキスト) を使用するだけです。

于 2009-04-23T03:55:41.670 に答える
33

これは、Black Horus の回答に対する Razor/MVC 3 (およびそれ以降) の更新です。

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)));
    }

}

.cshtml ファイルに次のように入力できます。

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

2013 年 10 月 31 日: image 要素に追加の HTML 属性を設定できるように、追加のパラメーターで更新されました。使用法:

@Ajax.ImageActionLink("../../Content/Delete.png", "Delete", "Delete", new { id = item.Id }, new AjaxOptions { Confirm = "Delete contact?", HttpMethod = "Delete", UpdateTargetId = "divContactList" }, new{ style="border: none;" })
于 2011-06-01T12:34:40.817 に答える
6

別の解決策は、独自の拡張メソッドを作成することです。

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

最後のパラメーターは列挙型 LinkOptions です。

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

そして、次のように使用できます。

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

このソリューションの説明全体をブログに投稿します: http://fknet.wordpress.com/

于 2009-01-16T16:50:44.343 に答える
5

http://asp.net/mvcのバージョン 7 の Contact Manager チュートリアルを参照してください。Stephen Walther には、画像である Ajax.ActionLink を作成する例があります。

于 2009-03-29T21:02:24.473 に答える
5

簡単に言えば、それは不可能です。あなたのオプションは、ImageActionLink を持つ独自の拡張メソッドを作成することです。それほど難しくありません。または、actionLink に属性を追加し、innerhtml をイメージ タグに置き換えます。

于 2008-12-04T19:07:12.293 に答える
4

MVC3、Html.ActionImageLink および Ajax.ActionImageLink

これらを手伝ってくれた他のすべての回答に感謝します。

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)));
}
于 2011-07-14T01:58:59.283 に答える
4

一般的な解決策: アクション リンク内に任意の Razor を含めます

Razor テンプレート デリゲートを使用すると、非常に自然な方法でアクション リンク内に任意の Razor コードを挿入できる、はるかに優れたソリューションがあります。したがって、画像やその他のコードを追加できます。

これは拡張メソッドです:

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));
}

使用方法は次のとおりです。

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

これにより、Razor を IntelliSense で記述し、テンプレートに必要な任意のオブジェクト (ViewModel、またはサンプルの車のようなその他のオブジェクト) を使用できます。また、テンプレート内の任意のヘルパーを使用して、画像や必要な要素をネストできます。

Resharper ユーザーへの注意事項

プロジェクトで R# を使用している場合は、R# 注釈を追加して 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)
于 2013-06-17T15:49:15.743 に答える
1

すべての答えは良いですが、私は最も簡単なものを見つけました:

@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;"
} )

リンク テキストに空白 (" ") を使用していることに注意してください。空のテキストでは機能しません。

于 2012-04-11T19:08:16.800 に答える
0

最初の解決策は、次のようなヘルパー静的メソッドDecodeLinkContentを使用することです。

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

DecodeLinkContentは、最初の'>'と最後の'<'を検索し、コンテンツをHttpUtility.Decode(content)に置き換える必要があります。

この解決策は少しハックですが、最も簡単だと思います。

于 2009-01-16T16:43:43.923 に答える
0

Html データ属性を使用する

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

を交換してください

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

自分のイメージで

于 2015-02-08T14:44:56.683 に答える
0

Templated Razor Delegatesを使用した MVC3 の更新は T4Mvc依存していますが、非常に強力です。

このページの他のさまざまな回答に基づいています。

        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);
        });
    }

許可:

@Ajax.WrapInActionLink(MVC.Deal.Details(deal.ID.Value),@<img alt='Edit deal details' src='@Links.Content.Images.edit_16_gif'/>, new AjaxOptions() { UpdateTargetId="indexDetails" })
于 2011-12-05T20:21:36.463 に答える
0

この拡張機能を使用して、glifyphicon で ajax リンクを生成します。

    /// <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));
    }
于 2014-11-09T20:48:47.773 に答える
0

すべてが非常に優れたソリューションですが、ソリューションに が含まreplaceれているのが嫌いな場合は、これを試すことができます。

{
    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);
}

さらに、私の場合、 を使用url.Content(imageUrl)しないと画像が表示されません。

于 2014-03-16T21:58:19.327 に答える
0

ここに素晴らしい解決策がありますが、アクションリンクに画像以外のものが必要な場合はどうすればよいでしょうか? これは私がそれを行う方法です:

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

欠点は、ボタン要素に少しスタイルを設定する必要があることですが、必要なすべての html をそこに配置できます。

于 2013-10-10T17:32:59.870 に答える
0

これに対する最良の解決策は、入力タグに 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]">
                }

簡単で速いです。

AjaxOptions に干渉する他のコントロール ライブラリと組み合わせて使用​​したので、将来別のセットを試す場合に備えて、System.Web.Mvc.Ajax.AjaxOptions 全体を入力する傾向があります。

注: これには MVC3 内で問題があるように見えることに気付きました (type="image" と関係があります)、MVC 4 でも機能します

于 2014-05-14T13:36:43.443 に答える
0

.li_inbox { background: url(inbox.png) no-repeat; パディング左:40px; /画像背景ワイト 40px / }


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

于 2013-08-05T16:14:12.807 に答える
-1
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)));

        }

    }

}
于 2013-03-11T15:15:04.070 に答える