Using JQuery Variable within Razor

一曲冷凌霜 提交于 2021-02-08 08:43:18

问题


How do you make use of a jquery variable within Url.Action within jquery?

var id = "10";
window.location.href = '@Url.Action("MyAction", "MyController", new { id })';

Thanks


回答1:


try, replace function by placing a token:

var id = "10";
var actionUrl = "@Url.Action("MyAction","MyController", new { Id= "TabId" })";
window.location.href = actionUrl.replace("TabId", id);



回答2:


If I understand you question correctly.. To achieve this I would make an Ajax call with your jQuery to a Razor page passing your jQuery parameters as GET/POST then retrieve the GET/POST on the Razor page and pass something back via Ajax.




回答3:


Jquery,javascript statements and variables are evaluated in browser. Razor is evaluated in web server. So you cannot do what you mean. But if you set value in a razor variable, you can use it on both razor and javascript code.




回答4:


You can't use a jQuery variable in Razor.
The reason why you can't use a javascript variable in razor is that razor runs in the server. Javascript runs in the client.

You could however store that url in a javascript variable and then use it to build the specific url you need, i.e.:

var url = '@Url.Action("MyAction", "MyController")';

window.location.href = url + "?id=" + id;

If you need to pass several parameters and you don't want to handle creating a string with ?param1=X&param2=Y etc you can use jQuery's param method, i.e.:

window.location.href = url + "?" + $.param({id:10, param2:"hello"});

$.param({id:10, param2:"hello"}) returns id=10&param2=hello




回答5:


Just to complete the set of possible answers, if your variable value is known server-side (you have not clarified that point) you can also inject Razor values into your javascript:

e.g.

var id = "@(myServerValue)";
window.location.href = @Url.Action("MyAction", "MyController", new { Id = myServerValue })) 

If the value is only known client-side, you can use a client-side replace as Zaheer Ahmed and Rui suggested.

If you need to handle null cases, and want to remove the extra param, I would go as far as using a regex to match the replacement:



来源:https://stackoverflow.com/questions/21626958/using-jquery-variable-within-razor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!