使用 JavaScript 为 MVC 应用程序构建相对 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9745139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:41:09  来源:igfitidea点击:

building relative URLs for an MVC app with JavaScript

c#javascriptasp.net-mvcknockout.jsrelative-path

提问by one.beat.consumer

I'm having trouble getting C# and JavaScript/jQuery to play nice here.

我在让 C# 和 JavaScript/jQuery 在这里玩得很好时遇到了麻烦。

I have a knockout view model, plain old javascript object... one of its property/methods fires off an .ajax()call, and the url parameter is built using some of its other property values (javascript variables).

我有一个淘汰赛模型,普通的旧 javascript 对象......它的一个属性/方法触发了一个.ajax()调用,并且 url 参数是使用它的一些其他属性值(javascript 变量)构建的。

This works fine when completely contained in JavaScript, but when deployed as an app to IIS, the relative pathing is hosed.

当完全包含在 JavaScript 中时,这可以正常工作,但是当作为应用程序部署到 IIS 时,相对路径会受到影响。

In MVC3 normally I would use something like @Url.Actionand let the server side build the address... but again, the trick is C# is unaware of the changing javascript values.

在 MVC3 中,我通常会使用类似的东西@Url.Action,让服务器端构建地址......但同样,诀窍是 C# 不知道不断变化的 javascript 值。

Code:

代码:

var viewModel = {
    vendors: ko.observableArray([]),
    count: ko.observable(10),
    page: ko.observable(1),
    filterText: ko.observable(""),
    submit: function () {
        $.ajax({
            // works fine, until deploy when it is no longer a site relative URL
            url: 'vendors/' + viewModel.count() + '/' + viewModel.filterText(),

            // does not work, because C# is unaware of the javascript variables.
            //url: @Url.Action("Vendors", "Home", new { count = viewModel.count(), filter = viewModel.filterText() })

            dataType: 'json',
            success: function (data) {
                viewModel.vendors(data);
            }
        });    
    }
    // next: // load sequence starting with (page+1 * count) 
    // previous: // load sequence starting with (page-1 * count)
};
ko.applyBindings(viewModel);


Question:

问题:

My question then is, how can I build the url for the ajax call using the javascript variable values (ex. count, filterText) and still map from the relative root of the application?

我的问题是,如何使用 javascript 变量值(例如 count、filterText)为 ajax 调用构建 url 并仍然从应用程序的相对根进行映射?

回答by jmoerdyk

The way we do this in my MVC 3 project is to include the following in the Master Layout:

我们在我的 MVC 3 项目中这样做的方法是在主布局中包含以下内容:

<script type="text/javascript">
    var baseSiteURL = '@Url.Content("~/")';
</script>

Then you just prepend that to your URLs in the JavaScript.

然后,您只需将其添加到 JavaScript 中的 URL 中即可。

Which in your sample would read:

您的示例中的内容如下:

url: baseSiteURL + 'vendors/' + viewModel.count() + '/' + viewModel.filterText()

回答by Darin Dimitrov

One possibility is to send those javascript values as request parameters:

一种可能性是将这些 javascript 值作为请求参数发送:

$.ajax({
    url: '@Url.Action("vendors")',
    data: { count: viewModel.count(), filter: viewModel.filterText() },
    dataType: 'json',
    success: function (data) {
        viewModel.vendors(data);
    }
});

Of course this implies that you are using default routes and the parameters will simply be sent to the server either as query string parameters (if you are using GET) or as part of the POST request body. In both cases you will fetch them on the server the same way:

当然,这意味着您使用的是默认路由,参数将简单地作为查询字符串参数(如果您使用 GET)或作为 POST 请求正文的一部分发送到服务器。在这两种情况下,您都将以相同的方式在服务器上获取它们:

public ActionResult Vendors(int count, string filter)
{
    ...
}

Another possibility, if you absolutely insist on having some custom routes for your AJAX requests, would be to use a simple string replace:

另一种可能性,如果您绝对坚持为您的 AJAX 请求设置一些自定义路由,将使用简单的字符串替换:

var url = '@Url.Action("vendors", new { count = "__count__", filter = "__filterText__" })';
url = url.replace('__count__', viewModel.count())
         .replace('__filter__', viewModel.filterText());
$.ajax({
    url: url,
    dataType: 'json',
    success: function (data) {
        viewModel.vendors(data);
    }
});

回答by one.beat.consumer

Darin's answer is the most solid, but it requires sending data using query string params on the ajax call.

Darin 的答案是最可靠的,但它需要在 ajax 调用中使用查询字符串参数发送数据。

To avoid that, I simply wrapped the @Url.Action()method in quotes and appended the javascript values as I intended.

为了避免这种情况,我只是将@Url.Action()方法用引号括起来,并按照我的意图附加了 javascript 值。

url: "@Url.Action("Vendors", "Home")/" + viewModel.count() + "/" + viewModel.filterText(),

Ultimately this produced the best results as it lets me keep a very clean url... Request.ApplicationPathseemed too hackish and can technically be null... @Url.Content()is intended for static "content" paths (ex. images, scripts)... etc.

最终这产生了最好的结果,因为它让我保持一个非常干净的 url ......Request.ApplicationPath看起来太hackish,技术上可以为空......@Url.Content()用于静态“内容”路径(例如图像,脚本)......等等。