MVC Core ajax POST error: 404(not found) and readyState 4 (completed)

 Author: Shengtao Zhou       Created: 1/10/2019 6:34:46 AM       Modified: 2/5/2019 4:11:36 AM   More...
The following code generates HTTP error 404 (not found) and readyState 4 (completed) error:

    var comment = {
Content: commentMsg
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-----------------------
    public JsonResult AddComment(PostCommentViewModel postComment)
        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

     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)

More...          Back to List          

(Please enter you comments between 100 to 2000 characters. Thanks for your contribution.) 

         Created:       Modified: 

Editing a comment

       (Please enter you comments between 100 to 2000 characters. Please login before edit comment.) 

div class="col-md-2">