Search code examples
c#ajaxasp.net-mvchttp-status-codes

MVC and fail AJAX call


I have a controller method:

    public async Task SaveRouting(string points, int tripId, decimal totalMileage)
    {
        if (Request.IsAjaxRequest())
        {
            //....
            await _serviceTrip.UpdateTotalMileageAsync(tripId, totalMileage);
        }
        else
            throw new Exception("Only ajax calls are allowed");
    }

so, as we can see, this method returns Task, so nothing to client. But if something wrong (i.e. totalMileage is less or equal 0) I want to return 422 status code and dictionary with invalid data, like: { "totalMileage" : "Total mileage should be greater than 0" }

How to do it? I try to do it:

            if (totalMileage <= 0)
            {
                Response.StatusCode = 422; // 422 Unprocessable Entity Explained
            }

but how to describe an error?


Solution

  • If you want to describe the error after setting Response.StatusCode, then you have to write into the body of the http response by calling Response.Body.Write(byte[],int, int). Therefore, you can convert your response message to a byte array using the following method:

    public byte[] ConvertStringToArray(string s)
    {
        return new UTF8Encoding().GetBytes(s);
    }
    

    And then use it like this:

    byte[] bytes = ConvertStringToArray("Total mileage should be greater than 0");
    Response.StatusCode = 422;
    Response.Body.Write(bytes,0,bytes.Length);
    

    But you can further simplify this using extension methods on ControllerBase