1

I've been working on setting up some Ajax.ActionLinks in my project. I can get the ActionLinks working 100%, however, my problem comes when I want to use an image instead of text for the link.

I've used a couple other StackOverflow posts and came up with the following solution to show an image inside an ActionLink:

Ajax.ActionLink("[replacethis]", "_Edit", "Account", new { id = "<#= UserId#>" }, new AjaxOptions() { UpdateTargetId = "subForm", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" }).ToHtmlString().Replace("[replacethis]", "<img src=\"" + Url.Content("~/Content/images/page-pencil-24.png") + "\" />"))

When I use a normal Ajax.ActionLink, my HTML looks like this:

<a href="/ct/administration/Account/_Edit/be71fdfc-0427-46e4-8ce5-6fa7cdf639d3" data-ajax-update="#subForm" data-ajax-mode="replace" data-ajax-method="GET" data-ajax="true">Edit</a>

When I use my new method my HTML looks like this:

<a href="/ct/administration/Account/_Edit/be71fdfc-0427-46e4-8ce5-6fa7cdf639d3" data-ajax-update="#subForm" data-ajax-mode="replace" data-ajax-method="GET" data-ajax="true">
<img src="/ct/Content/images/page-pencil-24.png">
</a>

When I put a break point in my controller and check if Request.IsAjaxRequest() == true, it's always False for the ImageActionLink, but True for the ActionLink.

Steve Sloka
  • 3,444
  • 2
  • 22
  • 29

1 Answers1

0

Looks like a common problem - there's an answer here that might be useful - a custom HtmlHelper to do this. There's another here in VB.NET.

Edit:

Looks like IsAjaxRequest looks for an HTTP Header (X-Requested-With) being set to XMLHttpRequest. You can force this by passing a GET/POST variable, though it's a bit hacky:

http://www.britishdeveloper.co.uk/2010/10/aspnet-mvc-isajaxrequest-jquery.html

However, interestingly you can also set this as either part of your form POST or even a GET querystring! Such as www.example.com?x-requested-with=XMLHttpRequest (case sensitive). This will also make IsAjaxRequest() return true.

Community
  • 1
  • 1
Danny Tuppeny
  • 40,147
  • 24
  • 151
  • 275
  • Thanks but my problem is getting the Ajax request to work. I can successfully show the image, but it only works as a new request. When I look at the Request.IsAjaxRequest() in my controller it's always false. When I switch back to using just text (even using my new function to show the image), then the request works. – Steve Sloka Oct 10 '11 at 14:37
  • Apologies - didn't read properly! Looks like IsAjaxRequest looks for an HTTP header, but it seems you can force it with the querystring if the method you're using doesn't/can't pass the header: http://www.britishdeveloper.co.uk/2010/10/aspnet-mvc-isajaxrequest-jquery.html – Danny Tuppeny Oct 10 '11 at 17:38