문제

ASP.NET MVC에는 Img 태그에 대한 Html.ActionLink 도우미에 해당하는 것이 있습니까?

동적으로 생성된 JPEG를 출력하는 컨트롤러 작업이 있고 ActionLink를 사용하여 HREF를 수행하는 것과 동일한 Lambda 표현식을 사용하여 이에 연결하고 싶었습니다.

또는 경로에 대한 URL만 제공하는 도우미(Lambda를 사용하여 다시 지정)도 허용됩니다.

편집하다:원래 Preview 5를 사용한다고 지정했는데 베타 버전이 출시된 것을 확인했습니다.따라서 곧 업그레이드할 수 있으므로 버전 번호는 불필요한 정보였습니다. :-)

도움이 되었습니까?

해결책

Url.Action()은 대부분의 Html.ActionLink 오버로드에 대한 기본 URL을 제공하지만 URL-from-lambda 기능은 지금까지 Html.ActionLink를 통해서만 사용할 수 있다고 생각합니다.어느 시점에서는 Url.Action에 유사한 오버로드를 추가할 수 있기를 바랍니다.

다른 팁

URL.Action 메소드를 사용할 수 있습니다.

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

이 질문은 오래되었으며 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에는 다른 오버로드도 많이 있습니다.

ActionLink에 텍스트 대신 마커를 배치한 다음 이를 이미지 코드로 바꾸는 해결 방법을 사용했습니다.이 같은:

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

가장 우아한 솔루션은 아니지만 작동합니다.

MVC3에서 링크는 다음과 같습니다.

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

ASP.NET MVC 베타에서는 다음을 사용할 수 있습니다. Html.BuildUrlFromExpression Futures 어셈블리의 메서드(기본 ASP.NET MVC 설치에는 포함되지 않지만 다음 위치에서 사용 가능) 코드플렉스) 다음과 같이 람다 스타일 ActionLink 구문을 사용하여 이미지 또는 HTML 주위에 링크를 만듭니다.

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

이미지 링크를 경계 없이 유지하려면 다음과 같은 CSS 규칙을 추가해야 합니다.

img
{
     border: none;
}

이 컨트롤을 사용할 수 있습니다. ActionLink처럼 동작합니다.

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

MVC 2에서는 달성하기가 매우 간단합니다.Url.Action 도우미에 대한 Lambda 표현식을 지원하기 위해 매우 간단한 확장 메서드를 직접 만들었습니다.MVC 2 Future를 참조해야 합니다.
코드는 다음과 같습니다.

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)); %>" />

포스팅이 너무 늦었지만 공유하고 싶습니다 :)

다음과 같은 새로운 확장 방법을 추가했습니다.

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

이것이 도움이 되었기를 바랍니다.

Url.Content()가 당신이 찾고 있는 것입니까?

Url.Content("~/path/to/something.jpg") 와 같은 것을 지정하면 애플리케이션 루트를 기반으로 적절한 경로로 변환됩니다.

-조롱

나는 위의 답변을 받아들여 약간의 래퍼 확장을 만들었습니다.

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

어쨌든 나를 위해 더 쉽게 만들었습니다. 다른 사람에게도 도움이 되기를 바랍니다.

나는의 출력을 넣으려고 노력했다. HTML.이미지 내 속으로 HTML.ImageLink 돕는 사람.

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

나에게 문제는 ActionLink 이름이 인코딩되어 < 대신 &lt가 있다는 것입니다.

방금 이 인코딩을 제거했는데 결과가 나에게 적합했습니다.(replace를 사용하는 대신 이 작업을 수행하는 더 좋은 방법이 있습니까?)

다른 게시물에 추가:제 경우에는(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());
        }

내부화 지원은 언어 경로를 통해 수행되었습니다 - 원본 소스 여기.

여기에서는 좋은 해결책이 있습니다. 하지만 액션링크에 이미지만 있는 것 외에 더 많은 것을 갖고 싶다면 어떻게 해야 합니까?이것이 내가 하는 방법이다:

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

단점은 여전히 ​​버튼 요소에 약간의 스타일을 적용해야 하지만 원하는 모든 HTML을 거기에 넣을 수 있다는 것입니다.

그리고 Ajax 도우미에서도 작동합니다. https://stackoverflow.com/a/19302438/961139

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top