ASP.NET MVC 重點教程一週年版 第五回 ActionResult的其它返回值

我們上邊所看到的Action都是return View();我們可以看作這個返回值用於解析一個aspx文件。而它的返回類型是ActionResult如

      public ActionResult Index()
        {
            return View();
        }

除了View()之外那我們這裏還能用於返回什麼值呢?

一、ascx頁面

場景:要返回代碼片斷,比如Ajax返回一個子頁

我們先新建一個Action

        public ActionResult Ascx()
        {
            return PartialView();
        }

我們下面再建一個View,仍然是在Action中點右鍵,AddView。

image 注意圖中勾選。

於是新建了一個ascx頁,我們將之少做改寫一下

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

<div>
得到一個DIV
div>

運行,得到頁面

image 

二、返回文本

除了上述情況,有時我們還會僅返回一段文本。

此時我們可以使用以下Action形式:

        public ActionResult Text(){
            return Content("這是一段文本");
        }

三、返回Json

有時我們在調用Ajax時還會要求返回對象爲Json序列化的結果,如:

        public ActionResult ShowJson()
        {
            var m = new EiceIndexModel
            {
                Name = "鄒健",
                Sex = true
            };
            return Json(m);
        }

返回文本:

{"Name":"鄒健","Sex":true}

四、輸出JS文件

大多時候js文件都是靜態的,但有時js文件可能也要動態生成這時我們可以這樣輸出

        public ActionResult Js()
        {
            return JavaScript("var x=0;");
        }

我們訪問之,得到一個正常頁面但其Content-Type:application/x-javascript; charset=utf-8

五、頁面跳轉

1.跳轉到Url

        public ActionResult rdurl()
        {
            return Redirect("http://www.baidu.com");
        }

2.跳轉到Action

        public ActionResult rdaction()
        {
            return RedirectToAction("Index","Eice");
        }

3.跳轉到Routing規則

        public ActionResult rdrouting()
        {
            return RedirectToRoute("Default",//Route名
              new{
                  Controller = "Eice",
                  Action = "Index"
              });
        }

六、顯示文件

        public ActionResult fn()
        {
            return File(
                "/Content/site.css"//文件路徑
                , "text/css"//文件類型
                );
        }

我們下一節講過濾器Filter。

發佈了174 篇原創文章 · 獲贊 5 · 訪問量 60萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章