使用 mvc5 API2 中的 ajax 错误函数返回字符串错误消息



我在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>= allowanceDto.MaxValue( 返回错误请求("最小值不能大于最大值"(;

这是 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");

           })

我的问题是当 IF 语句为 false 时,如何使用 ajax 显示 BadRequest 的字符串错误。

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");
  })

最新更新