Use Separate js File And use Url Helpers in it with ASP.NEt MVC 3 and Razor View Engine
Asked Answered
B

6

17

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.?

Britton answered 29/3, 2012 at 8:52 Comment(0)
J
32

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:

//In Your View
    @Html.Hidden("MyURL", Url.Action("Index"))

//In Your JS
    var myUrl = $("#MyURL").val();

    $.ajax({ url: myUrl , . . .
Jori answered 29/3, 2012 at 8:55 Comment(2)
Have you considered that this can open up security holes in the application? A hacker can replace the target URL on the server by simply modifying the value of hidden fields!Wilkerson
@Wilkerson Everything in a webpage can be modified by a so-called hacker, including the JavaScript files before they run. You can't stop this (even with encryption). The only time this would be a problem is if a hacker could modify the value of those hidden fields for other people.Baggs
K
8

The easiest way is just to create a global variable called something and just reference to it in your external JS

var baseURL = '@Url.Action("Index")';

Inside your external JS

$.ajax({ url: baseURL + "Action"
Kinsey answered 29/3, 2012 at 8:55 Comment(1)
Best practice is to namespace your global variables ``` if(!window.myProject){ window.myProject = {}; } myProject.baseURL = '@Url.Action("Index")'; ```Boyett
E
5

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.

Elveraelves answered 29/3, 2012 at 9:2 Comment(1)
The description URL given is not valid now. Can you please check that? Please update the URL if you know any. I am also in a need of that. Thanks in advance.Ellett
Y
2

There is no need to have hidden field, even this works too in the external .js file.

var myUrl = /ControllerName/ActionName;

$.ajax({ url: myUrl , . . 
Yep answered 7/12, 2014 at 8:31 Comment(0)
G
0

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.

Grinder answered 11/7, 2013 at 9:12 Comment(0)
D
0

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.

@Html.Hidden("AppUrl", Url.Content("~"))
Delsiedelsman answered 11/1, 2016 at 15:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.