我正在尝试对 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/