使用 Url.Action 和 jquery href attr 生成链接

generating link using Url.Action with jquery href attr

本文关键字:attr 链接 href jquery Url Action 使用      更新时间:2023-09-26

我正在尝试使用以下方法生成链接

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

我在某处读到我需要将此 Url.Action 与控制器隔离并操作到变量中,所以我尝试了这个

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

但这仍然不起作用。在浏览器中,我得到

http://localhost:1328/Home/Index2/@Url.Action%28%22Create%22,%20%22Home%22?clientId=181&clientName=undefined

另一种选择是存储带有data-*属性的 url 并访问它们。在视图中,您可以添加以下属性:

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

现在,您可以使用以下命令在脚本中访问它:

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

您的脚本应该位于 Razor 页面上@Url.Action以使帮助程序正常工作。

当你把它放在那里时,这应该可以工作:

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