How to report error to $.ajax without throwing exception in MVC controller?

前端 未结 7 557
天涯浪人
天涯浪人 2020-12-14 06:53

I have a controller, and a method as defined...

[HttpPost]
public ActionResult UpdateUser(UserInformation model){

   // Instead of throwing exception
   thr         


        
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 07:24

    This is where HTTP status codes come into play. With Ajax you will be able to handle them accordingly.

    [HttpPost]
    public ActionResult UpdateUser(UserInformation model){
        if (!UserIsAuthorized())
            return new HttpStatusCodeResult(401, "Custom Error Message 1"); // Unauthorized
        if (!model.IsValid)
            return new HttpStatusCodeResult(400, "Custom Error Message 2"); // Bad Request
        // etc.
    }
    

    Here's a list of the defined status codes.

提交回复
热议问题