I'm trying to send data to the server. But my code does not work. 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!
Remove the application/json
request header because you are not sending a JSON encoded 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 having your controller action directly take the Post
model instead of having each property as argument and then manually recopying them into a Post object:
[HttpPost]
public ActionResult SavePost(Post post)
{
var postRepository = new PostRepository();
postRepository.Add(post);
return Json(...);
}
The default model binder will take care of everything. Now if you wanted to use JSON as request you could use the JSON.stringify
method which is natively 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) { }
});
I have recently had similar problems with extJS and MVC but I use Charles to determine what requests are actually being sent and what response if any is being returned.
This tool is invaluable and I would highly recommend it!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With