画像をajaxアクションリンクとして機能させる方法はありますか? テキストを使用してのみ機能させることができます。ご協力いただきありがとうございます!
21 に答える
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" })%>
私が見つけた最も簡単な解決策は次のとおりです。
<%= Ajax.ActionLink("[replacethis]", ...).Replace("[replacethis]", "<img src=\"/images/test.gif\" ... />" %>
Replace() 呼び出しは、 imgタグをアクション リンクにプッシュするために使用されます。リンクを作成するための一時的なプレースホルダーとして、"[replaceme]" テキスト (またはその他の安全なテキスト) を使用するだけです。
これは、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;" })
別の解決策は、独自の拡張メソッドを作成することです。
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/
http://asp.net/mvcのバージョン 7 の Contact Manager チュートリアルを参照してください。Stephen Walther には、画像である Ajax.ActionLink を作成する例があります。
簡単に言えば、それは不可能です。あなたのオプションは、ImageActionLink を持つ独自の拡張メソッドを作成することです。それほど難しくありません。または、actionLink に属性を追加し、innerhtml をイメージ タグに置き換えます。
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)));
}
一般的な解決策: アクション リンク内に任意の 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)
すべての答えは良いですが、私は最も簡単なものを見つけました:
@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;"
} )
リンク テキストに空白 (" ") を使用していることに注意してください。空のテキストでは機能しません。
最初の解決策は、次のようなヘルパー静的メソッドDecodeLinkContentを使用することです。
DecodeLinkContent(Html.ActionLink<Home>(c => c.Delete(item.ID), "<span class=\"redC\">X</span>",new { Class = "none left"}))
DecodeLinkContentは、最初の'>'と最後の'<'を検索し、コンテンツをHttpUtility.Decode(content)に置き換える必要があります。
この解決策は少しハックですが、最も簡単だと思います。
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>
自分のイメージで
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" })
この拡張機能を使用して、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));
}
すべてが非常に優れたソリューションですが、ソリューションに が含ま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)
しないと画像が表示されません。
ここに素晴らしい解決策がありますが、アクションリンクに画像以外のものが必要な場合はどうすればよいでしょうか? これは私がそれを行う方法です:
@using (Ajax.BeginForm("Action", "Controler", ajaxOptions))
{
<button type="submit">
<img src="image.png" />
</button>
}
欠点は、ボタン要素に少しスタイルを設定する必要があることですが、必要なすべての html をそこに配置できます。
これに対する最良の解決策は、入力タグに 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 でも機能します
.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"
})
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)));
}
}
}