我有这个 json array-ish 变量,它从表中获取值:
var data = { "Model": [] };
$(".student-grade-data-row").each(function () {
data.Model.push({
'subjectId' : currentSubjectId,
'studentId': $(this).attr('id'),
'grade1' : $(this).find(".grade-select").val(),
'mult' : $(this).find(".mult-select").val(),
'subject': $(this).find(".topic-input").val(),
});
});
它类似于一个名为 grade
的 MVC 类
public partial class grade
{
public int id { get; set; } //auto-set
public int subjectId { get; set; }
public string studentId { get; set; }
public int grade1 { get; set; }
public int mult { get; set; }
public string subject { get; set; }
public System.DateTime date { get; set; } //auto-set
}
现在在完美的世界中,我希望将 data 变量中的值像这样发送到我的 Controller 中:
$.ajax({
url: '/Ajax/SendGrades',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: function (dt) {
console.log(dt);
}
});
然后我可以把它捡起来,并将它序列化为一个合适的对象列表。
问题是我什至看不到我真正发送给 Controller 的是什么以及我怎么可能将它链接到对象。
我尝试让函数接受类型为 List<grade> Model
的参数, 但它会一直告诉我该值为空。
我尝试使用一些基本的序列化,但也无法让它工作。代码
public ActionResult SendGrades(JsonResult Model)
{
List<grade> g = new List<grade>();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(grade));
g = (List<grade>)serializer.ReadObject(Model);
return Content("Hi");
}
给我一个错误提示
Cannot convert from System.Web.Mvc.JsonResult to System.IO.Stream
执行此操作的正确方法是什么,以便我以后可以将这些值安全地存储在我的数据库中?
我对这类工作还很陌生,所以对于任何菜鸟主义,我深表歉意。 在这里任何帮助都会很棒。
最佳答案
你的 ajax 选项需要包括
type: 'POST'
默认情况下,它是一个没有主体的 GET
,因此设置 contentType
是没有意义的,DefaultModelBinder
将不会使用 JsonValueProvider
(对于 GET
,数据格式需要为 data: { [0]subjectId: value, [0]studentId: value, [1] subjectId: value, [0]studentId: value, ....etc
- 即索引属性名称)
需要完整的代码
$.ajax({
url: '/Ajax/SendGrades',
type: 'POST', // add this
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: function (dt) {
console.log(dt);
}
});
和 Controller 方法
public ActionResult SendGrades(List<grade> model)
关于c# - 来自 Ajax 帖子的 JSON 到 MVC 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41799390/