Reputation: 3609
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
Upvotes: 1
Views: 1667
Reputation: 93561
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:
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:
Upvotes: 0
Reputation: 4886
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¶m2=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¶m2=hello
Upvotes: 0
Reputation: 28528
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);
Upvotes: 3
Reputation: 674
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.
Upvotes: 0
Reputation: 2731
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.
Upvotes: 0