Problem with ajax.actionlink helper, return string

2019-09-02 00:22发布

问题:

I'm using MVC3 with Razor. I have the following helper:

public static class ImageActionLinkHelper
    {
        public static string ImageActionLink(this AjaxHelper helper, string imageUrl, string actionName, object routeValues, AjaxOptions ajaxOptions)
        {
            var builder = new TagBuilder("img");
            builder.MergeAttribute("src", imageUrl);
            builder.MergeAttribute("alt", "");
            var link = helper.ActionLink(builder.ToString(TagRenderMode.SelfClosing), actionName, routeValues, ajaxOptions);
            return link.ToHtmlString();
        }
    }

and in my view I have:

@Ajax.ImageActionLink("../../Content/Images/button_add.png", "JobTasksNew", "TrackMyJob",new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "tmjDynamic" }))

and this is what i get when the page gets rendered

   <a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#tmjDynamic" href="/TrackMyJob/JobTasksNew?Length=10"><img alt="" src="../../Content/Images/button_add.png"></img></a>

Microsoft has an example with ajax.actionlink.Replace but I don't have this method. Can you help me get the correct html string?

Thank you in advance.

回答1:

Please try this:

public static class ImageActionLinkHelper {
        public static MvcHtmlString ImageActionLink(this AjaxHelper helper, string imageUrl, string actionName, object routeValues, AjaxOptions ajaxOptions) {
            var builder = new TagBuilder("img");
            builder.MergeAttribute("src", imageUrl);
            builder.MergeAttribute("alt", "");
            var link = helper.ActionLink("[replaceme]", actionName, routeValues, ajaxOptions);
            var html = link.ToHtmlString().Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing));
            return new MvcHtmlString(html);
        }
    }