0

I want to create in ASP.NET MVC 3 a link (in Ajax) with an image as background and no text. I'm using this method that creates an ajax link manually:

<a href="@Url.Action("Like", new { controller = "Article", like = 1, id = Model.Item1.ID })" data-ajax-update="#result" data-ajax-mode="replace" data-ajax="true"><div class="icon icon_like"></div></a>

The div tag calls the class "icon icon_like" of CSS that will import an image.

My question, is the following: There is no other way (maybe a helper) to being able to do this easily?

UPDATE: gdoron redirected me to a good link but it was not quite what I wanted (no Ajax support). For me, the first torm's answer is better, I only made some few changes to make it universal:

First in the helper it supports now a routeValues and changing the section that is to be updated

@helper AjaxImageLink(string action, Object routeValues, string icon_name, string sectionToUpdate = "#result"){
    <a href="@Url.Action(action, @routeValues)" data-ajax-update="@sectionToUpdate" data-ajax-mode="replace" data-ajax="true"><div class="icon @icon_name"></div></a>
}

About the use of that helper I'm using for the example in question:

@AjaxImageLink("Like", new { controller = "Article", like = 1, id = Model.Item1.ID }, "icon_like")

And it works as it should.

3 Answers3

0

use ajax.actionlink inside html.Raw and replace ajax.actionlink text with image tag. simple one line code.

@Html.Raw(@Ajax.ActionLink("[replacetext]", "Action", "Controller", new AjaxOptions { HttpMethod="Post"}).ToHtmlString().Replace("[replacetext]", ""))

0

You can see this question.

There are many others examples for it in the internet just google "asp.net mvc image action link"

Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367
0

To be compliant with DRY principle you can easily wrap your link structure in an inline helper like :

@helper AjaxLink(string action, string controller, string icon_name){
    <a href="@Url.Action(action, new { controller = controller, like = 1, id = Model.Item1.ID })" data-ajax-update="#result" data-ajax-mode="replace" data-ajax="true"><div class="icon @icon_name"></div></a>
}

other way would be to take ajax portion to unobtrusive reusable jquery binding :

<a href="@Url.Action("Like", new { controller = "Article", like = 1, id = Model.Item1.ID })" class="ajaxLink" ><div class="icon icon_like"></div></a>

$('.ajaxLink').click(function (e) {
    e.preventDefault();
    $("#result").load($(this).attr("href");
});
Paweł Staniec
  • 3,151
  • 3
  • 29
  • 41