将Google地理编码结果导入MVC控制器

问题描述:

我正在使用JavaScript API v3。我基本上对地址进行地理编码如下:将Google地理编码结果导入MVC控制器

geocoder.geocode({ 'address': address }, function (results, status) { 
    //Get results array here 
} 

这是成功的。我现在需要将该JSON传递给MVC控制器。我已经看到了很多方法来做到这一点,但我无法使用Geocode结果。

Haack:(我有一个复制结果结构的对象集合,最外层的对象是result[](见下文))。

geocoder.geocode({ 'address': address }, function (results, status) { 
    var jsonT = JSON.stringify(results);   
    $.ajax({ 
     url: '/Ctrl/Action', 
     type: "POST", 
     dataType: 'json', 
     data: jsonT, 
     contentType: "application/json; charset=utf-8", 
     success: function (result) { 
      alert(result.Result); 
     } 
    }); 
} 

控制器方法火灾,但是该值总是null

[HttpPost] 
    public ActionResult Action(GoogleGeoCodeResponse geoResponse) 
    { 
     //geoResponse is always null 
     return View(); 
    } 

我的谷歌类(S)

[Serializable] 
public class GoogleGeoCodeResponse 
{ 
    //public string status { get; set; } 
    public results[] results { get; set; } 

} 
[Serializable] 
public class results 
{ 
    public string[] types { get; set; } 
    public string formatted_address { get; set; } 
    public address_component[] address_components { get; set; } 
    public geometry geometry { get; set; } 
    public string partial_match { get; set; } 
} 
[Serializable] 
public class address_component 
{ 
    public string[] types { get; set; } 
    public string long_name { get; set; } 
    public string short_name { get; set; } 
} 
[Serializable] 
public class geometry 
{ 
    public location location { get; set; } 
    public string location_type { get; set; } 
    public viewport viewport { get; set; } 
    public bounds bounds { get; set; } 
} 
[Serializable] 
public class location 
{ 
    public string lat { get; set; } 
    public string lng { get; set; } 
} 
[Serializable] 
public class viewport 
{ 
    public southwest southwest { get; set; } 
    public northeast northeast { get; set; } 
} 
[Serializable] 
public class bounds 
{ 
    public southwest southwest { get; set; } 
    public northeast northeast { get; set; } 
} 
[Serializable] 
public class southwest 
{ 
    public string lat { get; set; } 
    public string lng { get; set; } 
} 
[Serializable] 
public class northeast 
{ 
    public string lat { get; set; } 
    public string lng { get; set; } 
} 

在撕掉我的头发后,我休息一下,然后在@Darin Dimitrov的帮助下马上找到问题。问题在于JSON与该对象不匹配。 GoogleGeoCodeResponse对象有一个results调用结果的数组,但是从Google返回的JSON有一组结果,但未命名。在我的stringify之前添加这个添加了正确的命名结构和所有绑定。

var o = { results: results }; 

假设你已经在Application_Start增加了JSON值提供者工厂:

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory()); 

和实际JSON请求您的视图模型相匹配签名:

{ geoResponse: { 
    results: [ 
     { types: [ 't1', 't2' ], formatted_address: 'abc', ... }, 
     { types: [ 't3', 't4' ], formatted_address: 'def', ... }, 
     ... 
    ] } 
} 

您应该成功获取控制器操作中的视图模型。此外,您可能不需要用[Serializable]修饰模型,因为XML和JSON序列化程序未使用该模型。它用于二进制序列化。

+0

谢谢,这帮助我找到我的答案。注意到'geoResponse'不正确,但是我的JSON也出错了让我失去了正确的轨道。 – 2011-05-11 06:04:13