47

ASP.NET MVC には、Img タグの Html.ActionLink ヘルパーに相当するものがありますか?

動的に生成された JPEG を出力するコントローラー アクションがあり、ActionLink を使用して HREF を行うのと同じラムダ式を使用してリンクしたいと考えました。

あるいは、ルートに URL を与えるだけのヘルパー (これも Lambda を使用して指定) も受け入れられます。

EDIT : 私はもともとプレビュー 5 を使用していると指定していましたが、ベータ版がリリースされていることがわかりました。したがって、バージョン番号は、すぐにアップグレードする可能性があるため、不要な情報でした:-)

4

14 に答える 14

47

URL.Actionメソッドを使用できます

<a href="<%= Url.Action("Create")  %>"><img src="../../Content/Images/add_48.png" /></a>
于 2009-07-23T15:33:55.027 に答える
39

この質問は古いもので、最近 RC が既にリリースされていたときに ASP.NET MVC を使い始めたばかりですが、私のように後でこの質問を見つけた人にとっては興味深いかもしれません。

少なくとも RC では、匿名型でも Url.Action() を使用できます。結果は上記の提案よりもはるかに良く見えます。

<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>

もちろん、RouteUrl には他にも多くのオーバーロードがあります。

于 2009-02-19T16:20:30.207 に答える
20

Url.Action() は、Html.ActionLink のほとんどのオーバーロードのベア URL を取得しますが、ラムダからの URL 機能は、これまで Html.ActionLink を介してのみ利用できると思います。うまくいけば、彼らはある時点で Url.Action に同様のオーバーロードを追加するでしょう。

于 2008-10-17T01:02:40.943 に答える
8

回避策を使用して、ActionLink のテキストの代わりにマーカーを配置し、それをイメージ コードに置き換えました。このようなもの:

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

最もエレガントなソリューションではありませんが、機能します。

于 2008-12-27T10:26:39.350 に答える
5

MVC3 では、リンクは次のようになります。

<a href="@Url.Action("Create")"><img src="../../Content/Images/add_48.png" /></a>
于 2011-04-25T20:44:39.553 に答える
4

ASP.NET MVCベータ版では、FuturesアセンブリのHtml.BuildUrlFromExpressionメソッド(デフォルトのASP.NET MVCインストールには含まれていませんが、CodePlexから入手できます)を使用して、イメージの周囲にリンクを作成できます。 HTML--次のようにラムダスタイルのActionLink構文を使用します。

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

画像リンクをフチなしに保つには、次のようなCSSルールを追加する必要があります。

img
{
     border: none;
}
于 2008-11-21T16:44:46.797 に答える
3

このコントロールを使用できます。ActionLinkのように動作します。

http://agilefutures.com/index.php/2009/06/actionimage-aspnet-mvc

于 2009-06-12T13:17:13.203 に答える
2

MVC 2 で実現するのは非常に簡単です。Url.Action ヘルパーの Lambda 式をサポートするために、独自の非常に単純な拡張メソッドを作成しました。MVC 2 Futures を参照する必要があります。
コードは次のとおりです。

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

これはあなたがそれを使用する方法です:

<img src="<%= Url.Action<YourController>(c => c.YourActionMethod(param1, param2)); %>" />
于 2010-05-06T05:33:19.047 に答える
2

投稿が遅すぎることはわかっていますが、共有したいです:)

次のような新しい拡張メソッドを追加しました。

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

これが役に立ったことを願っています。

于 2011-11-16T02:11:37.707 に答える
1

私は上記の答えを受け取り、ラッパー拡張機能を少し作成しました。

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

とにかく私にとっては簡単になりました、それが他の誰かを助けることを願っています。

于 2012-07-09T12:08:49.647 に答える
1

Url.Content() はあなたが探しているものですか?

Url.Content("~/path/to/something.jpg") のようなものを指定すると、アプリケーション ルートに基づいて適切なパスに変換されます。

-ジョシュ

于 2009-06-17T16:44:09.243 に答える
0

他の投稿への追加:私の場合(asp.net mvc 3)、画像リンクを言語セレクターとして機能させたかったので、最終的には次のようになりました:

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

内部化のサポートは、言語ルート (元のソースはこちら) を介して行われました。

于 2012-07-17T11:06:18.930 に答える
0

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

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

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

また、Ajax ヘルパーでも動作します: https://stackoverflow.com/a/19302438/961139

于 2013-10-10T17:40:13.960 に答える
0

Html.Imageの出力を Html.ImageLink ヘルパーに入れようとしまし

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

私にとっての問題は、ActionLink 名がエンコードされているため、< の代わりに < を使用していることです。

このエンコーディングを削除したところ、結果はうまくいきました。(replace を使用する代わりにこれを行うより良い方法はありますか?)

于 2011-01-08T13:13:31.710 に答える