I ask a similar question here and Darin Dimitrov
answer that we can't use Url helper like $.ajax({ url: '@Url.Action("Index")', . . .
in separate js file so what is your suggestion to use Url helper in view page and pass it to javascript, I don't want to use hard code url, I need to find it with Url helper.?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- MVC-Routing,Why i can not ignore defaults,The matc
- void before promise syntax
- Keeping track of variable instances
The easiest way is just to create a global variable called something and just reference to it in your external JS
Inside your external JS
I used a similar approach to raklos, but was looking to get the root directory path in all places, so I went with the code below.
Take a look at Generating External JavaScript Files Using Partial Razor Views. In this blog post, I describe how you can make use of regular Razor views and a custom action filter to render external JavaScript files that can have Razor code in them.
You can use RazorJS for that purpose. It allows writing Razor-Style C# or VB.NET inside your JavaScript files. There is a short description available here.
There is no need to have hidden field, even this works too in the external .js file.
var myUrl = /ControllerName/ActionName;
Use a hidden field to store your url, then use javascript to read the hidden field, then use that in your code. That way you can keep the JS file separate to the view. Something like this: