Igo*_*nko 6 json sencha-touch asp.net-mvc-3
我正在尝试将数据发送到服务器.但我的代码不起作用.有人能指出错误吗?
Sencha代码:
Ext.Ajax.request({
url: '/Blog/SavePost',
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
params: {
id: currentPost.data.Id,
title: currentPost.data.Title,
text: currentPost.data.Text,
authorName: currentPost.data.AuthorName,
authorEmail: currentPost.data.AuthorEmail,
postDate: currentPost.data.PostDate
},
failure: function (response) { },
success: function (response, opts) { }
});
Run Code Online (Sandbox Code Playgroud)
MVC代码:
[HttpPost]
public ActionResult SavePost(int id, string title, string text, string authorName, string authorEmail, DateTime postDate)
{
Post post = new Post { Id = id, Title = title, Text = text, AuthorEmail = authorEmail, AuthorName = authorName, PostDate = postDate };
var postRepository = new PostRepository();
postRepository.Add(post);
return Json();
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Dar*_*rov 10
删除application/json
请求标头,因为您没有发送JSON编码的请求:
Ext.Ajax.request({
url: '/Blog/SavePost',
method: 'POST',
params: {
id: currentPost.data.Id,
title: currentPost.data.Title,
text: currentPost.data.Text,
authorName: currentPost.data.AuthorName,
authorEmail: currentPost.data.AuthorEmail,
postDate: currentPost.data.PostDate
},
failure: function (response) { },
success: function (response, opts) { }
});
Run Code Online (Sandbox Code Playgroud)
我个人建议让你的控制器动作直接采用Post
模型,而不是将每个属性作为参数,然后手动将它们重新复制到Post对象:
[HttpPost]
public ActionResult SavePost(Post post)
{
var postRepository = new PostRepository();
postRepository.Add(post);
return Json(...);
}
Run Code Online (Sandbox Code Playgroud)
默认的模型绑定器将处理所有事情.现在,如果您想使用JSON作为请求,您可以使用JSON.stringify
本机内置于现代Web浏览器中的方法:
Ext.Ajax.request({
url: '/Blog/SavePost',
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
params: {
post: JSON.stringify({
id: currentPost.data.Id,
title: currentPost.data.Title,
text: currentPost.data.Text,
authorName: currentPost.data.AuthorName,
authorEmail: currentPost.data.AuthorEmail,
postDate: currentPost.data.PostDate
})
},
failure: function (response) { },
success: function (response, opts) { }
});
Run Code Online (Sandbox Code Playgroud)