How to access javascript variable in @ URL.Action ()

How can I access the JavaScript value inside @URL.Action() ? something like:

 <script type="text/javascript"> function name(myjavascriptID) { jQuery("#list_d").jqGrid('setGridParam', { url: '@URL.Action("download file", "download", new { id = <myjavascriptID> })', page: 1 }); } </script> 
+58
javascript asp.net-mvc asp.net-mvc-3 razor
Jun 23 2018-11-11T00:
source share
5 answers

You can not. JavaScript does not execute when creating the action url. What you can do is something like this:

 function name(myjavascriptID) { var link = '@Url.Action("download file", "download", new { id = "-1" })'; link = link.replace("-1", myjavascriptID); jQuery("#list_d").jqGrid('setGridParam', { url: link, page: 1 }); } 

NTN.

+105
Jun 23 2018-11-11T00:
source share

I am doing something pretty similar, but less verbose:

 var myUrl = '@Url.Action("Solution","Partner")/' + myjavascriptID; $.ajax.load(myUrl); // or whatever 

We can do this because of routing, and ultimately Url.Action with the parameters of the route dictionary is converted to a URI, which looks like this:

 http://localhost:41215/Partner/Solution?myJavascriptID=7 

Just a second choice, because, as a wise old man once said: "This is our choice, Harry, it shows that we are, in fact, much more than our abilities."

+8
Dec 28 '13 at 9:50
source share

You can pass variables to any link as shown below ...

 var url = '@Html.Raw(@Url.Action("MethodName", "ControllerName"))' + '?id = ' + myjavascriptID 
+5
Apr 7 '14 at 17:38 on
source share

You can create JavaScript code in C # as follows:

 function fun(jsId) { var aTag = '<a href="@Html.Raw(@Url.Action("ActionName", "ControllerName", new { objectId = "xxx01xxx" }).Replace("xxx01xxx", "' + jsId + '"))">LINK</a>'; } 

Here is the code from a question rewritten using this method:

 function name(myjavascriptID) { jQuery("#list_d").jqGrid('setGridParam', { url: '@Html.Raw(@URL.Action("download file", "download", new { id = "XXXmyjavascriptIDXXX" }).Replace("XXXmyjavascriptIDXXX", "' + myjavascriptID + '"))', page: 1 }); } 
0
Jun 24 '16 at 14:11
source share

In the same vein as Brian Mines, you can format the url string instead of replacing -1 with your variable, that is, if I, like me, you think it's better to read. The following answer assumes that you modified the String prototype as suggested in this answer :

 var url = unescape('@Url.Action("download file", "download", new { id = "{0}" })').format(myjavascriptID); 

A unescape call unescape necessary if you want to decode your {0} . I like this alternative because it makes it easy to select multiple parameters from JS variables. For example:

 var url = unescape('@Html.Raw(Url.Action("Action", "Controller", new { id = "{0}", name = "{1}" }))').format(myID, myName); 

I added Html.Raw in my second example to avoid & in the url string.

0
Jul 27 '16 at 16:09
source share



All Articles