Test.cshtml:
function insertButton(item) {
var options = {};
options.url = "/api/test";
options.type = "POST";
var obj = datas;
obj.name = $("#insertName").val();
obj.url = $("#insertUrl").val();
console.dir(obj);
options.data = JSON.stringify(obj);
options.contentType = "application/json";
options.dataType = "html";
options.success = function (msg) {
swal({ type: "success", title: msg, showConfirmButton: !1, timer: 2000 })
getAll();
},
options.error = function (msg) {
swal({ title: "ERROR", text: msg, icon: "error", type: "error", confirmButtonText: "OK" })
};
$.ajax(options);
}
测试控制器.cs
[HttpPost]
[Route("api/test")]
public async Task<IActionResult> InsertData([FromBody]Sites sites)
{
_context.Add(sites);
await _context.SaveChangesAsync();
return new ObjectResult($"{sites.Name} added");
}
如何向 Ajax"options.error"
返回消息? 并且模型中"[Required]"
Name
+Url
,但仍保存空字段...
好吧,您没有检查模型是否有效:
if (!ModelState.IsValid)
return new BadRequest(ModelState);
在行动开始时添加它,您就可以开始了。
或者,如果您使用的是 Core 2.1+ASP.NET 则只需将[ApiController]
属性添加到控制器类即可。然后,此检查将自动为您进行。