How to format a URL.Action() call in JQuery to set

2019-07-22 05:41发布

问题:

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.

回答1:

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);
    });
});


回答2:

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