从js到MVC控制器的JSON

JSON from js to MVC controller

本文关键字:JSON 控制器 MVC js      更新时间:2023-09-26

今天我试图从代码的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());
    }
}

您要添加到标记中的项具有属性latlongtitle,但您的视图模型(您试图序列化到的视图模型)具有不同的属性名称。所以我建议您创建一个具有相同属性名称的类

public class MarkerItem
{
  public string Title {set;get;}
  public decimal Lat {set;get;}
  public string Long { set;get;}
}

由于您想要发送一个标记数组,请使用上面类的集合作为参数。您不需要使用字符串作为参数并再次对其进行反序列化默认模型绑定器将能够将发布的数据映射到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());
}
相关文章: