根据Model Asp.net Core API验证Json String

时间:2019-01-30 04:01:14

标签: c# asp.net-core form-data modelstate

我需要将Model数据与Image一起发送,因此我正在使用FormData。由于我们无法直接传递模型,因此我正在使用JSON.stringify

如何针对Model验证此Json字符串(与我们进行ModelState验证一样)?

1 个答案:

答案 0 :(得分:2)

是的,您需要先从表单数据中提取模型 例如

var request = HttpContext.Current.Request;
var model = new yourViewModel();
model.field1 = request.Form["field1"];
model.field2 = request.Form["field2"];
model.Document = request.Files["Document"];

ModelState.Clear(); 
this.Validate(model); 
if (ModelState.IsValid) {

}

了解更多here