Use Separate js File And use Url Helpers in it wit

2019-01-23 04:05发布

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

6条回答
欢心
2楼-- · 2019-01-23 04:25

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"
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-23 04:28

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("~"))
查看更多
Fickle 薄情
4楼-- · 2019-01-23 04:29

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.

查看更多
闹够了就滚
5楼-- · 2019-01-23 04:40

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.

查看更多
我只想做你的唯一
6楼-- · 2019-01-23 04:41

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

var myUrl = /ControllerName/ActionName;

$.ajax({ url: myUrl , . . 
查看更多
我想做一个坏孩纸
7楼-- · 2019-01-23 04:44

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 , . . .
查看更多
登录 后发表回答