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.
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:
The response would look something like this, for example:
To receive this response, your ajax call needs modifying very slightly: