Hassan
Hassan

Reputation: 311

How can i make an image as an Ajax Action Link?

How can i make an image as an Ajax Action Link?

Upvotes: 0

Views: 198

Answers (3)

Jplum
Jplum

Reputation: 1

To push the id to the edit control whilst displaying an edit image instead of the word Spag you can try this:

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

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039140

You could do this:

<a href="<%: Url.Action("someaction", "somecontroller") %>" id="mylink">
    <img src="<%: Url.Content("~/images/foo.png") %>" alt="foo" />
</a>

and then in a separate javascript file AJAXify this link:

$(function() {
    $('#mylink').click(function() {
        $.ajax({
            url: this.href,
            type: 'GET',
            success: function(result) {
                alert('success');
            }
        });
        return false;
    });
});

And if you want to avoid the tag soup in your views you could write a custom helper:

public static class HtmlExtensions
{
    public static MvcHtmlString ImageLink(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues, object htmlAttributes, string imageSource)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
        var image = new TagBuilder("img");
        image.Attributes["src"] = urlHelper.Content(imageSource);
        var anchor = new TagBuilder("a");
        anchor.Attributes["href"] = urlHelper.Action(actionName, controllerName, routeValues);
        anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        anchor.InnerHtml = image.ToString(TagRenderMode.SelfClosing);
        return MvcHtmlString.Create(anchor.ToString());
    }
}

and then in your view simply:

<%: Html.ImageLink(
    "someaction", 
    "somecontroller", 
    null, 
    new { id = "mylink" }, 
    "~/images/foo.png"
) %>

and of course the process of AJAXifying it stays the same.

Upvotes: 1

rcravens
rcravens

Reputation: 8388

What about something like:

<a href='<%= Url.Action(...) %>'><img src='...' /></a>

Not certain if there is a helper that does this.

Bob

Upvotes: 0

Related Questions