Return string error message using ajax error funct

2019-09-21 15:18发布

I'm using API2 controller in mvc5, implementing CRUD operations. In POST method i have an if statement that return BadRequest() when IF statement result is false.

[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);


}

This is the IF statement i needs to show the string error message

if (allowanceDto.MinValue >= allowanceDto.MaxValue) return BadRequest("Min value cannot be greater than max value");

this is the ajax call:

     $.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");


           })

My question is how to show the string error for BadRequest when IF statement is false using ajax.

1条回答
Bombasti
2楼-- · 2019-09-21 15:57
return BadRequest(ModelState);

would return to the client a JSON object containing details of all the fields that failed validation. That's what people usually do in this situation. It will contain whatever messages you have defined in your validation attributes on the model.

You can also add custom messages to the model state before you return it, e.g:

ModelState.AddModelError("Allowance", "Min value cannot be greater than max value");
return BadRequest(ModelState);

The response would look something like this, for example:

{
  "Message":"The request is invalid.",
  "ModelState":{
    "Allowance":["Min value cannot be greater than max value"]
  }
}

To receive this response, your ajax call needs modifying very slightly:

  $.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");
  })
查看更多
登录 后发表回答