MVC之ActionResult


一、所有的Controller都繼承自System.Web.Mvc.Controller

  目前ASP.NET MVC3默認提供了多種ActionResult的實現,在System.Web.Mvc命名空間里。

  其中ActionResult是一個抽象類,所有一下的Result都繼承自它,因此如果一個Action的返回值是ActionResult的話,可以返回以下任意一種類型的值,但是如果限制死了返回值為以下任意一種Result,則只能夠返回指定的類型的數據了。

  • ContentResult
  • EmptyResult
  • FileResult
  • HttpStatusCodeResult
  • HttpNotFoundResult
  • HttpUnauthorizedResult
  • JavaScriptResult
  • JsonResult
  • RedirectResult
  • RedirectToRouteResult
  • ViewResultBase
  • PartialViewResult
  • ViewResult
        public ContentResult Index()
        {
            return Content("測試");       //瀏覽器顯示測試
        }

        public EmptyResult Index()
        {
            return new EmptyResult();     //瀏覽器顯示空白            
        }

        public FileResult Index()
        {
            return File(Server.MapPath("~/demo.jpg"), "application/x-jpg", "demo.jpg");        //瀏覽器直接下載demo.jpg   
        }

        public HttpNotFoundResult Index()
        {
            return HttpNotFound();     //報404錯誤          
        }

        public HttpUnauthorizedResult Index()
        {
            return new HttpUnauthorizedResult();     //未授權的頁面,跳轉到/Account/LogOn          
        }

        public JavaScriptResult hello()
        {
            string js = "alert('你還好嗎?');";
            return JavaScript(js);      //頁面顯示 alert('你還好嗎?');} 並不會執行這個js,要執行這個js可以在任意視圖里<script src="@Url.Action("hello")" type="text/javascript"></script>     
        }

        public JsonResult Index()
        {
            var jsonObj = new
            {
                Id = 1,
                Name = "小銘",
                Sex = "",
                Like = "足球"
            };

            return Json(jsonObj, JsonRequestBehavior.AllowGet);     //返回一個JSON,可以將此代碼輸出到JS處理展示
        }

        public RedirectResult Index()
        {
            return Redirect("~/demo.jpg");      //可以跳轉到任意一個路徑
            return Redirect("http://www.baidu.com");
            return Redirect("/list");
        }

        public RedirectToRouteResult Index()
        {
            return RedirectToRoute(     //跳轉到指定Action
            new
            {
                controller = "Home",
                action = "GetName"
            });
        }

        public ViewResult Index()
        {
            return View();          //這個是最常用的,返回指定視圖
            //return View("List");
            //return View("/User/List");
        }

        public PartialViewResult Index()
        {
            return PartialView();          //部分視圖,可以作為一個部分引入另外一個視圖中,跟View大致相同
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM