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
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);
regex replace like /[?&]Id=TabId/ etc instead would do that (if you want nulls). The problem with your example below is that it does handle other parameters (which happen frequently in using Action). You then need to handle ? and & cases.$.param({id: 10, someOtherParameter:20}) -> id=10&someOtherParameter=20You 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
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:
var id = "@(myServerValue)"and@Url.Action("MyAction", "MyController", new { Id = myServerValue }))