我正在尝试将数据发送到服务器.但我的代码不起作用.有人能指出错误吗?
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) { } });
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(); }
谢谢!
解决方法
删除application / json请求标头,因为您没有发送JSON编码请求:
Ext.Ajax.request({ url: '/Blog/SavePost',params: { id: currentPost.data.Id,postDate: currentPost.data.PostDate },opts) { } });
我个人建议你的控制器动作直接采用Post模型,而不是将每个属性作为参数,然后手动将它们重新复制到Post对象:
[HttpPost] public ActionResult SavePost(Post post) { var postRepository = new PostRepository(); postRepository.Add(post); return Json(...); }
默认的模型绑定器将处理所有事情.现在,如果您想使用JSON作为请求,您可以使用原生内置于现代Web浏览器中的JSON.stringify方法:
Ext.Ajax.request({ url: '/Blog/SavePost',headers: { 'Content-Type': 'application/json;charset=utf-8' },params: { post: JSON.stringify({ id: currentPost.data.Id,postDate: currentPost.data.PostDate }) },opts) { } });