今天我试图从我的 JS 代码部分获取 JSON 并将其传递给 C# 方法。 当我将结果传递给当前方法时,我得到 null 的问题。
这是我的 JS 部分:
GMaps.on('click',
map.map,
function(event) {
markers.push(new Point(map.markers.length, event.latLng.lat(), event.latLng.lng()));
var index = map.markers.length;
var lat = event.latLng.lat();
var lng = event.latLng.lng();
map.addMarker({
lat: lat,
lng: lng,
title: 'Marker #' + index
});
console.log(JSON.stringify(markers));
});
function TestJSON() {
$.ajax({
url: "@Url.Action("ReturnJson","Home")",
type: "POST",
data: JSON.stringify(markers),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
};
正如您从代码中看到的,在控制台中我看到标记数组不为空,并且在每次新单击后我都会向该数组添加一个值。 当我找到所有标记时,我想保存它,所以我为它制作了一个按钮。
这是我的数据模型:
public class TripPoint
{
public string Name { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
}
public class TripRoute
{
public List<TripPoint> route = new List<TripPoint>();
}
它看起来像我的 html 代码:
<form>
<button type="button" value="Save your route " onclick="TestJSON()"></button>
</form>
最后它看起来像应该获取 JSON 字符串的方法
[HttpPost]
public ActionResult ReturnJson(string json)
{
// **********************************
// PROBLEM HERE: json is null
// **********************************
TripRoute route = new JavaScriptSerializer().Deserialize<TripRoute>(json);
return new EmptyResult();
}
请帮助找出为什么我得到空字符串。
更新。
这是我的路线配置
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "ReturnJSON",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "ReturnJSON", id = UrlParameter.Optional }
);
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}
}
最佳答案
您要添加到标记的项目具有属性 lat
、long
和 title
,但是您的 View 模型(您正在尝试序列化到)具有不同的属性名称。所以我建议你创建一个具有相同属性名称的类
public class MarkerItem
{
public string Title {set;get;}
public decimal Lat {set;get;}
public string Long { set;get;}
}
并且由于您想要发送标记数组,因此请使用上述类的集合作为参数。您不需要使用字符串作为参数并再次反序列化它。 默认模型绑定(bind)器将能够将发布的数据映射到 MarkerItem
类对象的列表
public ActionResult ReturnJson(List<MarkerItem> markerItems)
{
//do something with markerItems list
// to do : Return something
}
我刚刚注意到你的路由配置。您不需要注册第二条路线。您的默认路由注册就足够了。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}
关于javascript - JSON从js到MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38774981/