MVC Controller Action only receiving nulls from AJAX

丶灬走出姿态 提交于 2019-12-25 19:04:55

问题


I have an ajax call that passes data for two parameters to a controller action. The action is called, but the parameters for the action always have null values (in this case the integer is its default of value of 0). I have made sure to check the packets sent by the ajax call and I do see the correct values I intend to send with the correct parameter/attribute names in stringified JSON.

Here is the Controller Action:

[HttpPost]
public IActionResult Summary(int courseID, String test)
{
    using (LearningCurveContext db = new LearningCurveContext())
    {
        Course course = db.Courses.Where(c => c.CourseId == courseID).FirstOrDefault();
        CourseSummary courseSummary = new CourseSummary
        {
            courseID = course.CourseId,
            courseName = course.Name,
            courseDescription = course.Description
        };

        return PartialView(courseSummary);
    }
}

Here is the Ajax call:

$(document).on("click", ".courseName", function ()
    {
        var element = this;
        $.ajax({
            url: $(element).attr("data-url"),
            type: "POST",
            data: JSON.stringify({ "courseID": "1", "test": "blah" }),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            cache: false,
            success: function (data)
            {
                $("#details-live").html(data);
            },
            error: function ()
            {
                alert("Could not load course summary");
            }
        });
    });

I have tried removing the content type option, as well as not stringifying the data and sending the value of courseID as 1 as well as "1". Nothing seems to work. The URL is correct as the action is being called and the code is run -- just the data doesn't seem to be bound.


回答1:


Because for Asp.Net core you have to be explicit about where the framework looks for the data. In this case you would need to specify [FromBody], but you would also have to refactor the code to use a model as you can only use that attribute once in the action.

public class CourseSummaryPostModel {
    public int courseID { get; set; }
    public String test { get; set; }
}

Action update

[HttpPost]
public IActionResult Summary([FromBody] CourseSummaryPostModel model) {        
    int courseID = model.courseID;
    String test = model.test;
    using (LearningCurveContext db = new LearningCurveContext()) {
        Course course = db.Courses.Where(c => c.CourseId == courseID).FirstOrDefault();
        CourseSummary courseSummary = new CourseSummary {
            courseID = course.CourseId,
            courseName = course.Name,
            courseDescription = course.Description
        };
        return PartialView(courseSummary);
    }
}

The Ajax remains that same as in the original post with the JSON.stringify

Reference Asp.Net Core: Model Binding




回答2:


$(document).on("click", ".courseName", function ()
{
  var element = this;
  $.post( $(element).attr("data-url"),{ courseID: "1", test: "blah" }, function( data ) {
    $("#details-live").html(data);
  });
});



回答3:


The problem was that I was using ASP.NET Core, not ASP.NET Framework. In core actions only bind a single object as a parameter, and does not like primitive types for binding either. My solution was to put the data I needed to pass into a single model object (rather than as multiple parameters).



来源:https://stackoverflow.com/questions/46638411/mvc-controller-action-only-receiving-nulls-from-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!