使用 ASP.NET MVC 在 JS 文件中为 jQuery 设置 ajax url [英] Setting ajax url for jQuery in JS file using ASP.NET MVC

查看:19
本文介绍了使用 ASP.NET MVC 在 JS 文件中为 jQuery 设置 ajax url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前对 MVC 操作执行 Ajax 调用时,我的 javascript 位于视图中,而不是它自己的 JS 文件中.

When doing a Ajax call to an MVC action currently I have my javascript inside the View, not inside its own JS file.

然后很容易做到这一点:

It is then very easy to do this:

var xhr = $.ajax({
     url: '<%= Url.Action("DisplayItem","Home") %>/' + el1.siblings("input:hidden").val(),
     data: { ajax: "Y" },
     cache: false,
     success: function(response) { displayMore(response, el1, xhr) }
});

...然后在 JS 中使用 Url.Action() 在 ajax 调用中包含 URL 非常简单.在没有硬编码 URL 的情况下,我怎么能移动它来做它自己的 JS 文件?

...then including the URL in the ajax call using Url.Action() inside the JS is pretty easy. How could i move this do its own JS file when without hard coding the URL?

推荐答案

这种方式充分利用了 MVC 路由,因此您可以充分利用 MVC 框架.灵感来自 stusmith 的回答.

This way fully uses MVC Routing so you can fully take advantage of the MVC framework. Inspired by stusmith's answer.

在这里,我在 ApplicationController 中有一个用于此 URL 的动态 javascript 的操作:

Here I have an action in ApplicationController for dynamic javascript for this URL :

 /application/js

我在这里包含静态文件是因为我只想下载一个主 JavaScript 文件.如果需要,您可以选择只返回动态内容:

I'm including static files here because I want just one master javascript file to download. You can choose to just return the dynamic stuff if you want:

     /// <summary>
    /// Renders out javascript
    /// </summary>
    /// <returns></returns>
    [OutputCache(CacheProfile = "Script")]
    [ActionName("js")]
    public ContentResult RenderJavascript()
    {
        StringBuilder js = new StringBuilder();

        // load all my static javascript files                    
        js.AppendLine(IO.File.ReadAllText(Request.MapPath("~/Scripts/rr/cart.js")));
        js.AppendLine(";");

        // dynamic javascript for lookup tables
        js.AppendLine(GetLookupTables());
        js.AppendLine(";");

        return new ContentResult()
        {
            Content = js.ToString(),
            ContentType = "application/x-javascript"
        };
    }

这是创建查找表的辅助函数.只需为您要使用的每个 RouteUrl 添加一行.

This is the helper function that creates our lookup table. Just add in a line for each RouteUrl you want to use.

    [NonAction]
    private string GetLookupTables() 
    {
        StringBuilder js = new StringBuilder();

        // list of keys that correspond to route URLS
        var urls = new[] {
            new { key = "updateCart", url = Url.RouteUrl("cart-route", new { action = "updatecart" }) },
            new { key = "removeItem", url = Url.RouteUrl("cart-route", new { action = "removeitem" }) }
        };

        // lookup table function
        js.AppendLine("// URL Lookuptable");
        js.AppendLine("$.url=function(url) {");
        js.AppendLine("var lookupTable = " + new JavaScriptSerializer().Serialize(urls.ToDictionary(x=>x.key, x=>x.url)) + ";");
        js.AppendLine("return lookupTable[url];");
        js.AppendLine("}");

        return js.ToString();
    }

这将生成以下动态 javascript,它基本上只是从任意键到我的操作方法所需的 URL 的查找表:

This generates the following dynamic javascript, which is basically just a lookup table from an arbitrary key to the URL I need for my action method :

// URL Lookuptable
$.url=function(url) {
var lookupTable = {"updateCart":"/rrmvc/store/cart/updatecart","removeItem":"/rrmvc/store/cart/removeitem"};
return lookupTable[url];
}

在cart.js 中我可以有这样的功能.注意url参数取自查找表:

In cart.js I can have a function like this. Note that the url parameter is taken from the lookup table :

 var RRStore = {};
 RRStore.updateCart = function(sku, qty) {

    $.ajax({

        type: "POST",
        url: $.url("updateCart"),
        data: "sku=" + sku + "&qty=" + qty,
        dataType: "json"

        // beforeSend: function (){},
        // success: function (){},
        // error: function (){},
        // complete: function (){},
    });

    return false;

};

我可以从任何地方调用它:

I can call it from anywhere with just :

 RRStore.updateCart(1001, 5);

这似乎是我能想到的唯一方法,可以让我以干净的方式使用路由.在 javascript 中动态创建 URL 很麻烦且难以测试.测试类型可以在此处的某处添加一层,以方便测试.

This seemed to be the only way I could come up with that would allow me to use routing in a clean way. Dynamically creating URLS in javascript is icky and hard to test. Testing types can add in a layer somewhere in here to easily facilitate testing.

这篇关于使用 ASP.NET MVC 在 JS 文件中为 jQuery 设置 ajax url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆