AJAX GET请求命中控制器但不在浏览器中访问URL

时间:2014-10-27 15:51:15

标签: javascript jquery ajax asp.net-mvc twitter-bootstrap

我正在实现bootstrap typeahead.js并尝试使用简单的AJAX GET请求,如下所示:

$("#find-company-search").typeahead({
    source: function (query, process) {
        var companies = [];
        map = {};

        // This is going to make an HTTP post request to the controller
        return $.post('/Companies/GetCompanies', { query: query }, function (data) {

            //console.log(data);

            // Loop through and push to the array
            $.each(data, function (i, company) {
                console.log(company);
                console.log(company.CompanyID);
                // Use the Name field on the display and for the map key.
                map[company.Name] = company;
                companies.push(company.Name);
            });

            // Process the details
            process(companies);
        });
    },
    updater: function (item) {
        console.log(item);
        console.log(map[item]);
        console.log(map[item].CompanyID);

        var selected = map[item].CompanyID;

        // Put ajax code to load the company here.
        $.ajax({
            url: "/companies/?companyID=" + selected,
            success: function() {
                alert("Success!");
            }
        });

        return item;
    }
});

当我发出请求时,它会命中以下控制器操作方法:

    public ActionResult Index() {
        if (CurrentUser.IsCompany(User)) {
            // We need to cast to a Company list
            return View(new List<Company> { db.Companies.Find(CurrentUser.CompanyID(User)) });
        }

        var filters = new Dictionary<string, int>();
        var companyID = 0;
        Int32.TryParse(Request.Params["companyID"], out companyID);

        filters["companyID"] = companyID;
        filters["hasTickets"] = Convert.ToInt32(Request.Params["has-tickets"] == "on");
        filters["hasDevices"] = Convert.ToInt32(Request.Params["has-devices"] == "on");
        filters["isCustomer"] = Convert.ToInt32(Request.Params["type"] == "customer");
        filters["isVendor"] = Convert.ToInt32(Request.Params["type"] == "vendor");
        filters["isLead"] = Convert.ToInt32(Request.Params["type"] == "lead");

        ViewBag.Filters = filters;

        var companies = db.Companies.Where(c => c.Hidden != true);

        ViewBag.CompaniesForDropdown = companies.ToList();

        if (filters.Count(filter => filter.Value <= 0) == filters.Count()) {
            // Return nothing if we haven't filtered. 
            return View(new List<Company>());
        }

        foreach (var filter in filters.Where(filter => filter.Value > 0)) {
            // <= 0 means false, or no selected company, so ignore those.
            switch (filter.Key) {
                case "companyID":
                    companies = companies.Where(c => c.CompanyID == companyID);
                    break;
                case "hasTickets":
                    companies = companies.Where(c => c.ServiceTickets.Count > 0);
                    break;
                case "hasDevices":
                    companies = companies.Where(c => c.Devices.Count > 0);
                    break;
                case "isCustomer":
                    companies =
                        companies.Where(c => c.Company_CompanyType.Count(t => t.CompanyType.Name == "Customer") > 0);
                    break;
                case "isVendor":
                    companies =
                        companies.Where(c => c.Company_CompanyType.Count(t => t.CompanyType.Name == "Vendor") > 0);
                    break;
                case "isLead":
                    companies = companies.Where(c => c.Company_CompanyType.Count(t => t.CompanyType.Name == "Lead") > 0);
                    break;
            }
        }

        return View(companies.OrderBy(c => c.Name).ToList());
    }

当我在输入中提交我的bootstrap typeahead的文本时,它会命中控制器并按预期填充companyID变量,但页面什么都不做。但是,如果我手动导航到浏览器中的URL(例如/ companies /?companyID = 1604),我的所有数据都会按预期显示。我的AJAX请求有问题吗?

编辑:我应该指定有问题的AJAX请求,即:

$.ajax({
    url: "/companies/?companyID=" + selected,
    success: function() {
        alert("Success!");
    }
});

2 个答案:

答案 0 :(得分:0)

您需要将页面导航到指定的网址:

updater: function (item) {
    var selected = map[item].CompanyID;

    window.location.replace("/companies", "/companies/?companyID=" + selected);
}

修改:根据Ngz的建议更改了答案。

答案 1 :(得分:0)

如果您想通过重定向页面向控制器发送请求,那么HTTP方法GET将完全满足您的需求。

Ajax的优点之一是 Web应用程序可以异步(在后台)向服务器发送数据和从服务器检索,而不会干扰现有页面的显示和行为。 < / strong>(通过Wikipadia

您为什么要使用Ajax调用?

在您的情况下,控制器中的方法返回查看为什么当您手动点击URL时,视图将按预期返回。