我想存储有关 map 上标记的地址和坐标的数据,因此我在 Infowindow 中创建按钮,该按钮会将我重定向到另一个 View 上的表单(也使用另一个 Controller )。我希望此表格已填写有关坐标和地址的数据。我有一个在按钮单击时调用的函数,其中包含 AJAX 代码,用于将 JSON 数据发送到 Controller 中的方法。问题是,单击按钮后,不会调用 Controller 方法(尽管函数调用在调试时可以正常工作)。我一直在寻找解决方案,但我真的不知道我做错了什么。
调用addMarker
:
google.maps.event.addListener(marker, 'click', function (event) {
if(infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: data});
infowindow.open(map, marker);
var buttonAdd = document.getElementById('addButton');
buttonAdd.onclick = function() {
addMarker(event.latLng, address);
}
});
JS函数与AJAX:
function addMarker(location, fulladdress) {
var data = JSON.stringify(fulladdress + location) //it's ok, i checked with firebug
$.ajax({
type: "POST",
url: "Incidents/Create",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: data
})
}
Controller :
public class IncidentsController : Controller
{
//some code
[HttpPost]
public ActionResult Create(string JsonStr)
{
return View();
}
//some code
}
现在我只是想进入另一个 View 而不对收到的数据做任何事情,但它不起作用。 ajax 或 Controller 肯定有问题。我是 MVC、JS 和 AJAX 的新手,所以如果有什么愚蠢的地方请原谅我。提前致谢。
TL;DR - 单击按钮应该会收到另一个 View ,其中包含部分填写的(包含地址和坐标)表单。
最佳答案
发现问题了。
您正在使用数据类型:“json”
。如果您想在 MVC 中发布 JSON
,那么您需要创建与您要发布的格式相同的适当模型。
看看下面的例子。
Controller :
public class JsonPostExampleController : Controller
{
[HttpPost]
public ActionResult JsonPost(JsonModel data)
{
return View();
}
}
Javascript:
$.ajax({
type: "POST",
url: "JsonPostExample/JsonPost",
dataType: 'json',
data: { 'name': 'ravi' },
success: function (data) { }
});
型号:
public class JsonModel
{
public string name { get; set; }
}
现在,根据您的要求,我们不能使用dataType: "json"
,因为您无法根据 Google 的完整地址和位置响应格式创建模型。
所以你需要使用dataType: "text"
,为此你只需要修改你的javascript。
使用以下内容更新您的 JavaScript block :
function addMarker(location, fulladdress) {
var data = JSON.stringify(fulladdress) + JSON.stringify(location)
$.ajax({
type: "POST",
url: "Incidents/Create",
dataType: "text",
data: { JsonStr : data }
});
}
并且您的 Controller 代码与以下内容相同:
public class IncidentsController : Controller
{
//some code
[HttpPost]
public ActionResult Create(string JsonStr)
{
return View();
}
//some code
}
现在您应该能够在服务器端获取字符串格式的数据。如果您想要 JSON
服务器端,那么您可以解析该字符串。
关于javascript - 使用 AJAX 将 json 数据从 Google map 传递到 MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34623965/