1

I'm fairly new to Mvc and ran into a problem try to use an Image as an Ajax Action link. I found a helper that I believe was posted by Stephen Walther...

using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace Helpers
{
    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));
        }

    }
}

However the "Replace" method does not exist in the version I'm using. (maybe an Mvc2 issue since I believe his contact manager app was an MVC1 app??) A quick search through the docs and I found the "Replace" method as obsolete and it was suggesed to use "MvcHtmlString.Create()" I tried a number of combinations in this helper using that method and I could not get the link to render with an image. I would either get a link pointing to the correct action/controller and the img tag as plain text OR vice versa a correctly rendered img with the link as plain text.

Just as a sidenote on almost all the combos I tried, I was returning a type MvcHtmlString instead of the standard string listed in this particular helper.

1 Answer 1

3

This is probably from when MvcHtmlString didn't exist yet. You should be able to make this work with Replace() method tho, just need to get the actual string it was supposed to work with in the first place:

var link = helper.ActionLink("[replaceme]", actionName, routeValues, ajaxOptions).ToString();
return link.Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing));
Sign up to request clarification or add additional context in comments.

4 Comments

When I add the helper, the project wont build because it says Replace() method doesnt exist.
Yes that's what I said. You have to call ToString() on the result you get from helper.ActionLink().
I'm sorry, i didnt see the ToString() at the end of your first line, definitely works now! Thanks!
Sweet. That fixed my problem going from MVC1 to MVC2. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.