Return string error message using ajax error function in mvc5 API2

梦想的初衷 提交于 2019-12-13 08:36:45

问题


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:


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


来源:https://stackoverflow.com/questions/43908484/return-string-error-message-using-ajax-error-function-in-mvc5-api2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!