javascript - 为什么 Ajax 调用没有被命中?

标签 javascript c# jquery ajax asp.net-mvc

我正在尝试对 map 上显示的数据应用过滤器,但由于某种原因,我设置的 Ajax 调用没有被执行。我可以到达 View 中的 console.log 行,但 Ajax 调用中此后的任何内容都不会执行。这是在 ASP.NET MVC 中完成的。

在这个项目中,我有来自其他开发人员的类似 Ajax 调用,它们的功能也类似。我尝试重组我的代码以类似的方式工作,但没有成功。其他开发者也不知道发生了什么。

Controller 中的 C#

[HttpPost]
public ActionResult MapFilter(string filterLake, bool filterPets)
{
    var filteredProperties = db.Properties.Include(a => a.PropertyCategory).Where(b => b.Status == true).Select(x => new { x.PropertyName, x.PropertyId, x.RatePerNight, x.RatePerWeek, x.MarketingTitle, x.Latitude, x.Longitude, x.Pets, x.PropertyCategory.PropertyCategoryName });

    if (filterLake != "")
        filteredProperties = filteredProperties.Where(a => a.PropertyCategoryName == filterLake);
    if (filterPets != true)
        filteredProperties = filteredProperties.Where(a => a.Pets == filterPets);

    var jsonProperties = JsonConvert.SerializeObject(filteredProperties);

    return new JsonResult()
    {
        Data = jsonProperties,
        JsonRequestBehavior = JsonRequestBehavior.AllowGet
    };
}

View 中的 JavaScript 和 Ajax

var filterLake, filterPets;
var btnApplyFilters = document.getElementById("applyFilters");
var filterLakeNode = document.getElementById("filterLake");
var filterPetsNode = document.getElementById("filterPets");

$(document).ready(function () {
    btnApplyFilters.onclick = function () {
        filterLake = filterLakeNode.options[filterLakeNode.selectedIndex].value;
        filterPets = filterPetsNode.options[filterPetsNode.selectedIndex].value;
        console.log("Lake:|" + filterLake + "| Pets:|" + filterPets + "|");
        $.ajax({
            url: "/Estates/MapFilter",
            type: "Post",
            data: {
                "filterLake": filterLake,
                "filterPets": filterPets
            },
            success: function (result) {
                filteredMapData = result;
                console.log("Result = " + result);
                loadMapMarkers(true)
            }
        });
    };
})

当我在本地主机上运行该程序时,我能够访问

console.log("Lake:|" + filterLake + "| Pets:|" + filterPets + "|");

线路没有问题。之后的任何内容都不会运行。

最佳答案

您需要检查filterPets值,它必须是true/false然后模型绑定(bind)器可以与bool类型映射。

对于原始类型(bool、int、float),您应该使用nullable类型bool?来防止值格式不正确。

[HttpPost]
public ActionResult MapFilter(string filterLake, bool? filterPets)
{
}

使用此参数,如果 filterPets 的值错误,则将为 null。

关于javascript - 为什么 Ajax 调用没有被命中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56780836/

相关文章:

javascript - addEventListener 不会在按键时触发

使用 AND 多个同级的 Jquery 选择器

javascript - 显示错误文档时获取 iframe 内容?

javascript - 如何使 $ (":text[placeholder]"在 IE 中工作

javascript - 在 Rails 中动态选择项目

javascript - jQuery 垂直居中文本仅在页面调整大小后加载

javascript - Highcharts问题: variable legend height

c# - ASP.NET MVC RSS 提要日期时间格式

c# - 尝试在 MailKit 中获取文件夹时出现异常,但在首先枚举文件夹时却没有

c# - 你如何在 C# 中直接类型转换一个盒装结构?