codememo

ASP.NET MVC Ajax이미지가 있는 ActionLink

tipmemo 2023. 3. 9. 22:05
반응형

ASP.NET MVC Ajax이미지가 있는 ActionLink

이미지가 Ajax 액션 링크 역할을 하도록 하는 방법이 있습니까?텍스트로만 작동시킬 수 있어요.도와주셔서 감사합니다!

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의 답변에 대한 레이저/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일: 이미지 요소에 대한 추가 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/에 게재합니다.

간단한 대답은 그것이 가능하지 않다는 것이다.ImageActionLink를 사용하기 위한 확장 메서드를 직접 작성할 수도 있습니다.actionLink에 속성을 추가하고 innerhtml을 이미지 태그로 바꿉니다.

http://asp.net/mvc 의 Contact Manager Tutorial 버전7 을 참조해 주세요.Stephen Walther는 Ajax를 만든 예를 가지고 있다.이미지인 ActionLink.

MVC3, HTMLAction Image Link 및 Ajax.액션 이미지 링크

다른 모든 답변에 감사드립니다.

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

일반적인 해결책: 액션 링크에 원하는 모든 면도기 포함

레이저 템플릿 딜러를 사용하여 매우 자연스러운 방식으로 작업 링크에 레이저 코드를 삽입할 수 있는 훨씬 더 나은 솔루션이 있습니다.이미지나 다른 코드를 추가할 수 있습니다.

확장 방식은 다음과 같습니다.

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

이를 통해 레이저를 인텔리센스로 쓰고 템플릿에 원하는 객체(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로 대체해야 합니다.디코딩(콘텐츠).

이 해결방법은 조금 어렵지만 나는 그것이 가장 쉽다고 생각한다.

템플레이트 레이저 대리인을 사용한 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" })

.li_background { background : url ( spading . png ) no - padding - left : 40px ; / image background wight 40px / }


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

이거 드셔보세요

@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()))

훌륭한 솔루션이지만, 액션 링크에 단순한 이미지 이상을 포함시키고 싶다면 어떻게 해야 할까요?방법은 다음과 같습니다.

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

단점은 아직 버튼 엘리먼트에 약간의 스타일링을 해야 하는데 원하는 html을 모두 넣을 수 있다는 것입니다.

모두 매우 좋은 솔루션이지만, 만약 당신이 이 솔루션을 가지고 있는 것이 싫다면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)이미지가 표시되지 않습니다.

지금까지 가장 좋은 해결책은 타입="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에 간섭하는 다른 컨트롤 라이브러리와 함께 사용했기 때문에 시스템 전체를 타이핑하는 경향이 있습니다.Web.Mvc.Ajax.Ajax Options는 나중에 다른 세트를 시도하게 될 경우를 대비해서 사용합니다.

참고: MVC3(type="image"와 관련된 문제)에 대해 알 수 있지만 MVC 4에서는 작동합니다.

glifyphicon을 사용하여 Ajax 링크를 생성하려면 이 Extension을 클릭합니다.

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

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>

자신의 이미지로

다른 사람들은 나를 위해 일하지 않았다.ToHtmlString()이 MVC 4에서 문자열을 뱉었습니다.

다음에서는 편집 컨트롤에 ID를 전달하고 텍스트스패그 대신 편집 이미지를 표시합니다.

@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") + "\" />"))
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)));

        }

    }

}

모르겠어요, 이게 더 쉬울 것 같아요.

    <a href="@Url.Action("index", "home")">
        <img src="~/Images/rocket.png" width="25" height="25" title="Launcher" />
    </a>

언급URL : https://stackoverflow.com/questions/341649/asp-net-mvc-ajax-actionlink-with-image

반응형