简体   繁体   中英

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

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

Another option is to store the url with data-* attributes and access them. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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