Send JSON data from Sencha Touch to ASP.NET MVC

I am trying to send data to a server. But my code is not working. Can someone point out a mistake?

Sencha Code:

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 Code:

 [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(); } 

Thanks!

+6
source share
2 answers

Remove the application/json request header because you are not sending the requested JSON request:

 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) { } }); 

Personally, I would recommend that your controller action directly accepts the Post model instead of having each property as an argument, and then manually rewriting them into a Post object:

 [HttpPost] public ActionResult SavePost(Post post) { var postRepository = new PostRepository(); postRepository.Add(post); return Json(...); } 

The default binder will take care of everything. Now, if you want to use JSON as a request, you can use the JSON.stringify method, which is built into modern web browsers:

 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) { } }); 
+10
source

I recently had similar issues with extJS and MVC, but I use Charles to determine which requests are actually sent and which response if any is returned.

This tool is invaluable and I would highly recommend it!

+2
source

Source: https://habr.com/ru/post/891133/


All Articles