MVC Controller Action仅接收来自AJAX的空值 [英] MVC Controller Action only receiving nulls from AJAX
问题描述
我有一个ajax调用,它将两个参数的数据传递给控制器操作。调用该操作,但操作的参数始终具有空值(在这种情况下,整数的默认值为0)。我已经确保检查ajax调用发送的数据包,并且我确实看到了我打算使用字符串化JSON中的正确参数/属性名称发送的正确值。
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.
这是控制器动作:
[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);
}
}
以下是Ajax调用:
$(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");
}
});
});
我尝试删除内容类型选项,以及不对数据进行字符串化并发送值courseID为1以及1。似乎没什么用。在调用操作并运行代码时,URL是正确的 - 只是数据似乎没有绑定。
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.
推荐答案
问题是我使用的是ASP.NET Core,而不是ASP.NET Framework。在核心操作中,只将单个对象绑定为参数,并且不喜欢用于绑定的基本类型。我的解决方案是将我需要的数据传递给单个模型对象(而不是多个参数)。
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).
这篇关于MVC Controller Action仅接收来自AJAX的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!