[英]AJAX Call not hitting Controller Method - ASP.NET MVC
我尝试在Controller方法中设置断点。 但这并不止于此。 警报“已单击”,下一个警报运行良好。 但是未调用controller方法。 任何帮助表示赞赏。 这是我的ajax调用和控制器方法。
var Url = "@Url.Action("~/Home/Get_Location")";
$("#gotoloc").click(function() {
alert("clicked");
alert(lat +" "+ lon);
$.ajax({
type: "POST",
url: Url,
data: {
latitude: lat,
longitude: lon
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Hello:" + response)
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
alert("ignored");
});
public JsonResult Get_Location(double latitude,double longitude)
{
string loc = latitude + "/" + longitude;
return Json(loc, JsonRequestBehavior.AllowGet);
}
您使用的Url.Action
方法不正确。
尝试这个
var Url = "@Url.Action("Get_Location","Home")";
上面的重载将操作方法名称作为第一个参数,并将控制器名称作为第二个参数
另外,我看到您传递了不正确的contentType请求标头。 contentType标头告诉服务器客户端正在发送的数据类型是什么。 您当前的代码表示您正在发送json数据。 但是您的操作方法中有2个参数,并且json序列化程序将无法正确将发布的数据映射到它,因此您将从服务器获得500响应。
假设您的页面中没有其他js错误,这应该可以工作
var url = "@Url.Action("Get_Location","Home")";
$.ajax({
type: "POST",
url: url,
data: { latitude: 44, longitude: 55 },
success: function (response) {
console.log("Hello:" + response);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.