When to use JsonResult over ActionResult

前端 未结 4 714
时光取名叫无心
时光取名叫无心 2020-12-29 23:57

I\'ve been unable to find a concrete answer regarding this question. I\'ve viewed posts and subsequent posts from this question and elsewhere but all I\'ve really come out o

4条回答
  •  隐瞒了意图╮
    2020-12-30 00:27

    You may have noticed that the names of all the common return types in an MVC controller end with "result", and more often than not, most actions return an ActionResult. If you look at the documentation, you can see that several, more specalized result types, inherit from the abstract class ActionResult. Because of this, you can now return an ActionResult in all of your actions, and even return different types. Example:

    public ActionResult View(int id)
    {
        var result = _repository.Find(id);
        if(result == null)
            return HttpNotFound(); //HttpNotFoundResult, which inherits from HttpStatusCodeResult
        return View(result); //ViewResult
    }
    

    All of this makes it easier to return different content, based on the request. So why would you use JsonResult over ActionResult? Perhaps so there are no misunderstandings, and you indeed only can return JSON, perhaps for readability, or some other personal preference.

提交回复
热议问题