我有一个看起来像这样的课程:
public class TaskRequest
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Title { get; set; }
[Required]
public string Body { get; set; }
[Required]
[Column(TypeName = "datetime2")]
public DateTime RequestedDateTime { get; set; }
public virtual Employee Employee { get; set; }
}
无论如何我可以设置一个HttpPost
方法,可以在ASP.NET
中创建要插入数据库的模型吗?
我目前的任务发布方法:
// POST /api/taskrequests
[HttpPost]
public TaskRequest CreateTaskRequest(TaskRequest taskRequest)
{
if (!ModelState.IsValid)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
_context.TaskRequests.Add(taskRequest);
_context.SaveChanges();
return taskRequest;
}
我目前正在使用HttpGet
获取员工并将stringify
整个TaskRequest作为JSON字符串
var task = new Object();
task.Title = taskTitle;
task.Body = taskBody;
task.RequestedDateTime = new Date(taskDate + " " + taskTime);
task.Employee = JSON.stringify(employee);
var jsonString = JSON.stringify(task);
然后将其发送到我的API,但员工始终为空。
答案 0 :(得分:1)
我认为你应该只调用一次JSON.stringify:
var task = new Object();
task.Title = taskTitle;
task.Body = taskBody;
task.RequestedDateTime = new Date(taskDate + " " + taskTime);
var employee = new Object();
//add employee properties here
task.Employee = employee;
var jsonString = JSON.stringify(task);
答案 1 :(得分:0)
据我所知,你应该编写自定义模型绑定器,在ASP.net mvc中你不能绑定复杂模型,除了简单模型,你应该实现IModelBinder接口并注册它
尝试查看这些链接
https://www.codeproject.com/Articles/605595/ASP-NET-MVC-Custom-Model-Binder
http://www.c-sharpcorner.com/article/custom-model-binding-in-asp-net-mvc/