2017-01-03 41 views
2

这是谷歌API - Javascript代码发送JSON对象参数网页API控制器.netCore

var output = new Object(); 
output.PlaceID = place.place_id; 
output.Longitude = place.geometry.location.lng(); 
output.Latitude = place.geometry.location.lat(); 

$.ajax({ 
    headers: { 
     'Accept': 'application/json', 
     'Content-Type': 'application/json' 
    }, 
    url: 'api/StorePlaces/Get', 
    type: 'POST', 
    data: { "value":output }, 
    success: function (result) { 
     // Do something with the result 
    } 
}); 

如何接收在控制器

// GET api/values/5 
    [HttpPost("{PlaceDetails}")] 
    public string Get(PlaceDetails value) 
    { 
     return "value"; 
    } 

在这种情况下,我得到空值

我无法发送字符串,如果我可以发送该对象,那就更好了。

这可以作为接收对象

public class PlaceDetails 
{ 
    public string PlaceID { get; set; } 
    public string Longitude { get; set; } 
    public string Latitude { get; set; } 
} 

enter image description here

+0

变更请求类型AJAX为“POST”,改变你的方法要接受POST和更改参数类型为“PlaceDetails” – Dalton

+0

@Dalton我得到空值,做什么 –

+0

修改数据:放''data:output'并删除'[FromBody]' – Dalton

回答

7

有许多东西你的代码错误,也许先请教几个初学者教程?

首先,你必须看看你发送的对象,这是非常明显的!

您发送

{ 
    "value" : { 
     "PlaceID" : "", 
     "Longitude " : "", 
     "Latitude " : "" 
    } 
} 

当预期的答案是

{ 
    "PlaceID" : "", 
    "Longitude " : "", 
    "Latitude " : "" 
} 

所以,你必须在JavaScript中使用此:

$.ajax({ 
    headers: { 
     'Accept': 'application/json', 
     'Content-Type': 'application/json' 
    }, 
    url: 'api/StorePlaces/Get', 
    type: 'POST', 
    // do not wrap it in object with value property here!!!! 
    data: JSON.stringify(output), 
    success: function (result) { 
     // Do something with the result 
    } 
}); 

其次,你的控制器动作(为什么当它是一个发布请求时,它叫做Get?)... [HttPost("{PlaceDetails}")]属性显然是错误的。

这将预计在路线中的参数为PlaceDetails。你不是这样的!只要删除它。此外,[FromBody]属性丢失告诉它从HTTP请求体反序列化模型

[HttpPost] 
public string Get([FromBody]PlaceDetails value) 
{ 
    return "value"; 
} 
+0

感谢您的解决方案。 –

+16

是的很好的答案,但作为初学者的夸张无论如何都帮助他?它会帮助其他人看到薄薄的侮辱吗?它真的让你感觉好点了吗? –