开发者

Generate link in JQuery using ASP.NET MVC Url.Action

I'm generating the list of links like this:

$('#la开发者_JS百科testNews').append('<li><a href="<%= Url.Action("Details", "Article") %>/' + key + '">' + val + '</a></li>');

And on the Index page link looks like:

<a href="/En/Article/Details/6">Title</a>

But, on the /En/Article/Details/6 page - generated link looks like:

<a href="/En/Article/Details/6/6">Title</a>

I've tried $('#latestNews').append('<li><a href="<%= Url.Action("Details", "Article") %>?id=' + key + '">' + val + '</a></li>'); It works ok, but then caching does not work.

My controller code:

[OutputCache(Duration = Int32.MaxValue, VaryByParam = "id,language", SqlDependency = "database:Articles")] //Articles will be added rarely so i think it'll be nice to cache them
public ActionResult Details(string id, string language)
{..}

My route:

routes.MapRoute(
                "Default", 
                "{language}/{controller}/{action}/{id}",
                new { language = "En", controller = "Home", action = "Index", id = UrlParameter.Optional } 
            );

So how to generate Url in a better way?

UPDATED:

 $.post('<%= Url.Action("GetLatest", "News") %>', function (data) {               
                $.each(data, function (key, val) {
                    $('#latestNews').append('<li><%= Url.ActionLink(val, "Details", "Article", new { id = key }, null) %></li>');                    
                });
                $('#news').show();
            }, "json");


Your key & val variables are in JavaScript so that isn't going to work with the Url Helper. You could change your script to look something like this:

EDIT: fixed bug - changed {id = null} to { id = String.Empty }

 $.post('<%= Url.Action("GetLatest", "News") %>', function (data) {               
                $.each(data, function (key, val) {
                    $('#latestNews').append('<li><a href="<%= Url.Action("Details", "Article", new { id = String.Empty}) %>/' + key +'">' + val + '</a></li>');                    
                });
                $('#news').show();
            }, "json");

So, the MVC Url.Action() method is just giving you the first part of the url. Then jQuery will add key onto the end of the url and add val as the text for the anchor at runtime.

I think that's the easiest way of doing it without refactoring the code too much.


The better way to generate the link is to pass the id directly to the Action method (and not to append it manually). Even better is to use the ActionLink instead of the Action method:

$('#latestNews').append('<li><%= Url.ActionLink(val, "Details", "Article", new { Id = key }, null) %></li>');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜