Line error message using ajax error function in mvc5 API2

I am using controller API2 in mvc5 implementing CRUD operations. In the POST method, I have an if statement that returns a BadRequest () value when the IF statement result is not correct.

[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 an IF statement that needs to be shown a string error message

if (allowanceDto.MinValue> = allowanceDto.MaxValue) return BadRequest ("The minimum value cannot exceed the maximum 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 line error for BadRequest when IF statement is false using ajax.

-1


source to share


1 answer


return BadRequest(ModelState);

      

returns a JSON object to the client containing information about all fields that failed validation. This is what people usually do in this situation. It will contain any messages that you have defined in your model validation attributes.

You can also add personalized messages to the model state before they are returned, for example:

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

      



The answer will look something like this:

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

      

To get this answer, your ajax call needs very little modification:

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

      

+1


source







All Articles