简体   繁体   English

MVC和AJAX调用失败

[英]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. 因此,正如我们所看到的,此方法返回Task,因此对客户端没有任何影响。 But if something wrong (ie 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" } 但是,如果出现问题(例如totalMileage小于或等于0),我想返回422状态代码和带有无效数据的字典,例如:{“” totalMileage“:”总里程数应大于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? 但是如何描述一个错误呢?

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) . 如果要在设置Response.StatusCode之后描述错误,则必须通过调用Response.Body.Write(byte[],int, int)写入http响应的正文。 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 但是您可以使用ControllerBase扩展方法进一步简化此操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM