C# Can';t使用MVC保存JSON数据
我正在使用MVC4.5,并试图将一个对象保存到SQL Server数据库中 我的对象如下所示:C# Can';t使用MVC保存JSON数据,c#,jquery,json,asp.net-mvc,C#,Jquery,Json,Asp.net Mvc,我正在使用MVC4.5,并试图将一个对象保存到SQL Server数据库中 我的对象如下所示: [{ "name": "Title", "value": "Test" },{ "name": "Description", "value": "Some text" },{ "name": "Duration", "value": "15 minutes" }] jquery AJAX是: $.ajax({ url: '@Ur
[{
"name": "Title",
"value": "Test"
},{
"name": "Description",
"value": "Some text"
},{
"name": "Duration",
"value": "15 minutes"
}]
jquery AJAX是:
$.ajax({
url: '@Url.Action("NewAppSave","App")',
dataType: "json",
type: "POST",
accept: 'appication/json; charset=utf-8',
cache: false,
data: { model: jsonData },
success: function (data) {
if (data.success) {
alert("Met succes !");
}
},
error: function (xhr) {
alert('error');
}
});
在控制器中,我创建了以下内容:
[HttpPost]
public JsonResult NewAppSave(Appointment model)
{
if (ModelState.IsValid)
{
using (var db = new MainDbContext())
{
var appointment = db.Appointments.Create();
appointment.UserId = 1;
appointment.Title = model.Title;
appointment.Description = model.Description;
appointment.Duration = model.Duration;
db.Appointments.Add(appointment);
db.SaveChanges();
}
}
else
{
ModelState.AddModelError("", "Something went wrong");
}
return Json(model);
}
看起来没有数据发送到控制器。我的代码有什么问题?您发送的对象应该直接提供给
数据(即不在模型参数中),属性名称必须与约会类匹配,ModelBinder才能工作。使用此函数定义-public JsonResult NewAppSave(列表模型)为了绑定到该模型,您的对象必须是数据:{Title:'test',Description:'Some text',Duration:'15 minutes'}
在这种情况下,约会对象必须具有name和value属性。非常感谢大家!使用一些代码,我成功地将对象重新写入正确的格式。您发送的对象应直接提供给数据(即不在模型参数中),并且属性名称必须与约会类相匹配,ModelBinder才能工作。使用此函数定义-public JsonResult NewAppSave(列表模型)为了绑定到该模型,您的对象必须是数据:{Title:'test',Description:'Some text',Duration:'15 minutes'}
在这种情况下,约会对象必须具有name和value属性。非常感谢大家!通过一些代码,我成功地将对象重新写入正确的格式。