我在mvc5中使用API2控制器,实现了CRUD操作。 在POST方法中,我有一个if语句,在IF语句时返回BadRequest() 结果是假的。
[HttpPost]
public IHttpActionResult CreateAllowance(AllowanceDto allowanceDto)
{
allowanceDto.AllowanceID = _context.Allowances.Max(a => a.AllowanceID) + 1;
allowanceDto.Encashment = true;
allowanceDto.Exemption = true;
allowanceDto.ExemptionValue = 0;
allowanceDto.ExemptionPercentage = 0;
allowanceDto.CreatedDate = DateTime.Now;
allowanceDto.ModifiedDate = DateTime.Now;
if (!ModelState.IsValid)
return BadRequest();
if (allowanceDto.MinValue >= allowanceDto.MaxValue)
return BadRequest("Min value cannot be greater than max value");
var allowanceInfo = Mapper.Map<AllowanceDto, Allowance>(allowanceDto);
_context.Allowances.Add(allowanceInfo);
_context.SaveChanges();
// allowanceDto.AllowanceID = allowanceInfo.AllowanceID;
return Created(new Uri(Request.RequestUri + "/" + allowanceInfo.AllowanceID), allowanceDto);
}
这是我需要显示字符串错误消息的IF语句
if(allowanceDto.MinValue&gt; = allowanceDto.MaxValue) 返回BadRequest(“最小值不能大于最大值”);
这是ajax电话:
$.ajax({
url: "/api/allowances/",
method: "POST",
data: data
})
.done(function () {
toastr.success("Information has been added
successfully","Success");
})
.fail(function () {
toastr.error("Somthing unexpected happend", "Error");
})
我的问题是如何使用ajax在IF语句为false时显示BadRequest的字符串错误。
答案 0 :(得分:1)
return BadRequest(ModelState);
将向客户端返回一个JSON对象,其中包含验证失败的所有字段的详细信息。这就是人们在这种情况下通常会做的事情。它将包含您在模型上的验证属性中定义的任何消息。
您还可以在返回之前将自定义消息添加到模型状态,例如:
ModelState.AddModelError("Allowance", "Min value cannot be greater than max value");
return BadRequest(ModelState);
响应看起来像这样,例如:
{
"Message":"The request is invalid.",
"ModelState":{
"Allowance":["Min value cannot be greater than max value"]
}
}
要接收此响应,您的ajax调用需要稍微修改:
$.ajax({
url: "/api/allowances/",
method: "POST",
data: data
dataType: "json" // tell jQuery we're expecting JSON in the response
})
.done(function (response) {
toastr.success("Information has been added successfully","Success");
})
.fail(function (jqXHR, status, err) {
console.log(JSON.stringify(jqXHR.responseJSON)); //just for example, so you can see in the console what the returned data is.
toastr.error("Somthing unexpected happened", "Error");
})