-1

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.

0

1 Answer 1

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");
  })
Sign up to request clarification or add additional context in comments.

10 Comments

Should i change the return in the api ` public IHttpActionResult CreateAllowance(AllowanceDto allowanceDto) {` could you please explain how to retunr JSON ?
web API returns JSON by default, unless you've overridden it somewhere. There should be no need to change the return type of the method - IHttpActionResult is a generic interface representing any result (OK, NotFound, etc etc). Whether it comes out as JSON, XML, text or whatever to the client depends on your API's serialisation settings, not on the return type.
P.S. I've just added to the answer because I noticed you wanted to return a custom string not specific to the validation on any particular field, as well.
i read an article that use ModalState in BadRequest(), but how to receive the error in ajax error(fail) function
Hi I've updated it again to show you. You receive it just like any other ajax error, except that it's formatted as JSON. Then you can process the object and display the relevant errors to the user.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.