2

I need to set the href attribute of a link to point to a specific image, which has its id from the database set as its title. However, I am having trouble with trying to format the string to include a call to get the title attribute of the image.

Here is the base string:

$("#favoriteLink").hover(function() {
    $(this).attr("href", '<%: Url.Action("FavoriteWallpaper", "Wallpaper", new{wallpaperId='+$(this).children.attr("title")+'}) %>');
});

favoriteLink is a div and the child is just one image.

Anonymous
  • 57
  • 1
  • 5

2 Answers2

3

Oh no, you can't mix server side code and javascript as you are trying to. How about this:

$('#favoriteLink').hover(function() {
    var title = $(this).children.attr('title');
    $(this).attr('href', function() {
        var url = '<%= Url.Action("FavoriteWallpaper", "Wallpaper", new { wallpaperId= "_TITLE_TO_REPLACE_"}) %>';
        return this.href.replace('_TITLE_TO_REPLACE_', title);
    });
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I have a new issue now. I need a way to check whether the wallpaper has been favorited in order to know which image to show, a black star, or a yellow star when the user hovers over the image. The easiest way I could think of was using a Dictionary, with the id of the image serving as the key, and a bool representing the favorite status as the value. However, since the id of the image is set as the title, I don't know how in the world I would go about getting the correct value. – Anonymous Jun 15 '11 at 21:29
0

You're URL.Action is rendered serverside and your javascript client-side. You wont have access to dom elements when you're trying to build the link.

You should get the actual URL thats rendered in URL.Action and build the string client-side

Amin Eshaq
  • 4,034
  • 1
  • 17
  • 21