The following code generates HTTP error 404 (not found) and readyState 4 (completed) error:
--------JavaScript-------------------
var comment = {
Content: commentMsg
};
$.ajax({
type: 'POST',
url: '/Posts/AddComment")',
data: { comment: comment },
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
success: function (response) {
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
----------C# Model class-----------------
public class PostCommentViewModel
{
public string Content { get; set; }
}
--------C# Controller-----------------------
[HttpPost]
public JsonResult AddComment(PostCommentViewModel postComment)
{
_context.Add(postComment);
_context.SaveChangesAsync();
return Json(postComment);
}
========================================
My problem is resolved. It seems MVC Core has some change from MVC for model binding. Here're the tricks:
1. In javascript, create an Object that matches your C# ViewModel class signature
var comment = new Object();
comment.PostId = @Model.Id;
comment.Content = commentMsg;
comment.UserId = "@Model.UserId";
comment.CreateTime = dateTimeNow.toLocaleString();
2. Pass data converted by JSON.stringfy
$.ajax({
type: 'POST',
url: '/Posts/AddComment',
data: JSON.stringify(comment),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
3. Add [FromBody] to C# controller action method
public JsonResult AddComment([FromBody] PostCommentViewModel comment)