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

我怕爱的太早我们不能终老 提交于 2019-11-28 23:19:41

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

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"

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;

$.ajax({ url: myUrl , . . 

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.

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("~"))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!