【问题标题】:Return string error message using ajax error function in mvc5 API2使用 mvc5 API2 中的 ajax 错误函数返回字符串错误消息
【发布时间】:2017-10-10 01:07:56
【问题描述】:

我在 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 语句

如果(allowanceDto.MinValue >=allowanceDto.MaxValue) return 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");


           })

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

【问题讨论】:

    标签: jquery ajax api asp.net-mvc-5


    【解决方案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");
      })
    

    【讨论】:

    • 我应该更改 api 中的返回 `public IHttpActionResult CreateAllowance(AllowanceDto allowedDto) {`你能解释一下如何返回 JSON 吗?
    • web API 默认返回 JSON,除非你在某处覆盖了它。不需要更改方法的返回类型 - IHttpActionResult 是一个表示任何结果(OK、NotFound 等)的通用接口。它是否以 JSON、XML、文本或其他形式出现在客户端取决于您的 API 的序列化设置,而不是返回类型。
    • P.S.我刚刚添加到答案中,因为我注意到您还想返回一个自定义字符串,而不是特定于任何特定字段的验证。
    • 我读了一篇文章,在 BadRequest() 中使用 ModalState,但是如何在 ajax error(fail) 函数中接收错误
    • 您好,我已经再次更新它以向您展示。您会像收到任何其他 ajax 错误一样收到它,只是它被格式化为 JSON。然后您可以处理该对象并向用户显示相关错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2011-08-20
    相关资源
    最近更新 更多