我正在尝试将列表发布到我的MVC控制器..
控制器: // POST api/UserFollows
public HttpResponseMessage PostUserFollows(List<FollowItem> followItemList)
{
//I'M GETTING NULL IN followItemList
if(followItemList==null)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
输出:
STATUS 400 Bad Request <-- Means I got null in followItemList
TIME 4025 ms
Cache-Control →no-cache
Connection →Close
Content-Length →0
Date →Tue, 29 Jan 2013 09:38:31 GMT
Expires →-1
Pragma →no-cache
Server →ASP.NET Development Server/10.0.0.0
X-AspNet-Version →4.0.30319
FollowItem
班级
namespace Helpers.SubClasses
{
public class FollowItem
{
public bool action;
public long FollowsUserId;
}
}
我尝试了很多请求,但没有一个是有效的..我总是得到空的!
后方法:
function postFollowList() {
$.ajax( {
url: Request_Url + "api/UserFollows",
type: 'post',
data: {
{action: true, FollowsUserId: 123456777},
{action: true, FollowsUserId: 123456888}
},
dataType: 'json',
success: function( data )
{
$('#newmovie').html("OK");
},
error: function (jqXHR, textStatus, err)
{
$('#newmovie').html('Error: ' + err);
}
});
请求: //作为JSON - 我正在使用POSTMAN
1.
[
{"action":"true","FollowsUserId":"123456777"}
]
2.
[
{action: true, FollowsUserId: 123456777},
{action: true, FollowsUserId: 123456888}
]
3.
{[
{action: true, FollowsUserId: 123456777},
{action: true, FollowsUserId: 123456888}
]}
4.
{followItemList:[
{action: true, FollowsUserId: 123456777},
{action: true, FollowsUserId: 123456888}
]}
null示例:
我尝试了很多.. 有人可以帮帮我吗? 感谢!!!
修改
答案是,当我需要发送application/xml
时,我在内容类型中发送了application/json
。
答案 0 :(得分:1)
JSON似乎无效。也许试试这个:
[
{
"action": true,
"FollowsUserId": 123456777
},
{
"action": true,
"FollowsUserId": 123456888
}
]
检查JSON有效性的一个好工具是jsonlint.com。
答案 1 :(得分:1)
我试过了 -
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
var foo = new List<FollowItem>()
{
new FollowItem {action = true, FollowsUserId = 123456777},
new FollowItem {action = true, FollowsUserId = 123456888}
};
return new JsonResult {Data = foo, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
//
// POST: /Home/
public ActionResult Dump(List<FollowItem> followItems)
{
Debug.WriteLine(followItems);
return new HttpStatusCodeResult(200);
}
}
public class FollowItem
{
public bool action;
public long FollowsUserId;
}
发布此内容 -
[
{"action":true,"FollowsUserId":123456777},
{"action":true,"FollowsUserId":123456888}
]
这很有效。请注意,这也是它发送响应的方式。
答案 2 :(得分:1)
尝试将变量名称添加到数据中。请参阅以下代码。
function postFollowList() {
$.ajax( {
url: Request_Url + "api/UserFollows",
type: 'post',
data: { followItemList: [
{action: true, FollowsUserId: 123456777},
{action: true, FollowsUserId: 123456888}
]},
dataType: 'json',
success: function( data )
{
$('#newmovie').html("OK");
},
error: function (jqXHR, textStatus, err)
{
$('#newmovie').html('Error: ' + err);
}
});
编辑:也许您可以在发布之前尝试序列化数组:
data: { followItemList: JSON.stringify([
{action: true, FollowsUserId: 123456777},
{action: true, FollowsUserId: 123456888}
])},