简体   繁体   中英

Jquery Append Parameter inside <a href='@Url.ActionLink()'></a>

I have the below code inside a Jquery function

$.each(array, function (index, value) {
                var id1 = value.match(/\d+/);
                $("#linksList").append("<li>" + value + "<a href='@Url.ActionLink("Details", "Jira", new { id ="${id1}" })'>" + value + "</a>" + "</li>");
            });

But I am not able to pass the parameter Id . I am getting random values assigned for Id as below . What am I doing wrong .

<a href="/Jira/Details/%2Bid1%2B"> jira_subtask_link 41102</a>

This is not possible to mix because Razor exists server side while jquery is client side

Templating engines inject your C# code into the HTML/CSS/Js prior to its run. As such ASP .NET cannot render such a variable intelligible when it is ready to compile to client side source code, as that var's life cycle is client side/while the app is running. Its a compile time vs run time discrepancy

I think you may be better off

  1. Saving that javascript variable to something you can send back to the controller
  2. At the controller level, putting it into a model that can be passed to the view
  3. Rendering the action link with that id as a variable coming from the view's model, and not from jQuery

I know it sounds a bit weird, but this is how server and client side code interact in templating engines

Additionally, a hacky approach may be to insert a "dummy" id string, and then using jQuery to replace that dummy text with your intended, actual id value

razor 代码在服务器端编译并转换为 html,客户端无法理解 razor 语法,因此如果您想从客户端获得相同的结果,则必须使用 javascipt

这种方式对我有用

 $("#linksList").append("<li>" + "" + "<a href='/JIra/Details/" + id + "'>" + value + "</a>" + "</li>");

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