简体   繁体   English

使用带有jquery href attr的Url.Action生成链接

[英]generating link using Url.Action with jquery href attr

I'm trying to generate a link using following 我正在尝试使用以下链接生成链接

$(this).parent().attr('href', '@Url.Action("Create", "Home"' + '?clientId=' + clientId + '&clientName=' + clientName);

somewhere I read that I need to isolate this Url.Action with controller and action into variable so I tried with this 我读过某个地方,我需要将带有控制器的Url.Action和action隔离到变量中,所以我尝试了

var a = '@Url.Action("Create", "Home"';
$(this).parent().attr('href', a + '?clientId=' + clientId + '&clientName=' + clientName);

But this still doesn't work. 但这仍然行不通。 In browser I'm getting 在浏览器中

http://localhost:1328/Home/Index2/@Url.Action%28%22Create%22,%20%22Home%22?clientId=181&clientName=undefined HTTP://本地主机:1328 /主页/索引2 / @ Url.Action%28%22Create%22%20%22Home%22的clientId = 181&CLIENTNAME =未定义

Another option is to store the url with data-* attributes and access them. 另一种选择是使用data-*属性存储URL并访问它们。 In the View you can add the below attribute: 在视图中,您可以添加以下属性:

data-url='@Url.Action("Create", "Home")'

Now you can access this in the script with: 现在,您可以使用以下命令在脚本中访问此文件:

var base = $(this).data('url');
$(this).parent().attr('href', base + '?clientId='+ clientId +'&clientName=' + clientName);

Your script should be on Razor page in order to make @Url.Action helper work. 您的脚本应该在Razor页面上,以使@Url.Action帮助程序起作用。

When you place it there this should work: 当您将其放置在此处时,它应该起作用:

//this line should generate /Home/Create string
var urlNoParam = '@Url.Action("Create", "Home")';
//and here you just add params as you want
$(this).parent().attr('href', urlNoParam  + '?clientId=' + clientId + '&clientName=' + clientName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM