0

To create an image button that calls an action method you can use construction like that

<a href="@Url.Action("SomeAction")" ><img src="image.jpg"/> </a>

But what if I actually need an ajax call? I can use jQuery, and bind a javascript event to the button, but I wonder if there is even an easier way, without polluting markup with scripts?

iLemming
  • 34,477
  • 60
  • 195
  • 309

2 Answers2

2

try

@Ajax.ActionLink("LinkText", "ActionName", "ControllerName", your route values or null, new AjaxOptions { UpdateTargetId="Div1"}, new { @class = "MyCssClass" })

in your css file

.MyCssClass
{
  background-image:url(image.jpg);
}

Edit

@Ajax.ActionLink("LinkText", "ActionName", "ControllerName", your route values or null, new AjaxOptions { UpdateTargetId = "Div1" }, new { style = "background-image:url(image.jpg)" })

Note

you should wirte the full path of your image(relative path).

Amir Ismail
  • 3,865
  • 3
  • 20
  • 33
  • can I do the background-image right there in the markup using @style? – iLemming Jun 16 '11 at 15:29
  • yes you can but you have not to use `@`, I used it because `class` is a reserved keyword in .net and cannot be used as variable name. – Amir Ismail Jun 16 '11 at 15:32
  • it doesn't let me create an action link with an empty string (first parameter) – iLemming Jun 16 '11 at 15:35
  • I show's me the text... which I don't want. And if I leave the text empty(spaces), it wouldn't show the background... – iLemming Jun 16 '11 at 15:52
  • I've managed that putting a few non breakable spaces @Ajax.ActionLink("\u00A0 \u00A0 \u00A0", but it still shows me a hyperlink underscore... Is there any way to hide it though css? – iLemming Jun 16 '11 at 16:00
  • I kind of trying to achieve the same thing, but I need to put an image together with a text and I cannot do it. Here is the link to my question: https://stackoverflow.com/questions/51622524/mvc-is-that-possible-to-ajax-actionlink-with-an-image-and-the-text-on-the-right?noredirect=1#comment90214971_51622524 – gene Aug 01 '18 at 14:46
0

I used a variation of this that works with a bit less finagling

https://stackoverflow.com/a/23656271/2667818

It's quick and works well with everything that I've tried it on.

Added benefit is that you can reuse existing css for images instead of rewriting them for buttons.

Community
  • 1
  • 1
  • I have noticed that this does appear to have issues within MVC3 (something to do with type="image"), it does work for MVC 4 though – James Pusateri May 14 '14 at 13:45