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

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

问题描述

在做一个Ajax调用的MVC行动目前我有我的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) }
});

...然后包括使用 Url.Action()里面的JS是pretty的容易Ajax调用的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 此网址的操作进行动态的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动态创建URLS是恶心和难以测试。测试类型可以在一层某处这里加入到轻松方便测试。

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.

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

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