MVC Controller return 格式

來源:互聯網
上載者:User

標籤:

所看到的Action都是return View();我們可以看作這個傳回值用於解析一個aspx檔案。而它的傳回型別是ActionResult如

public ActionResult Index() 
{ 
return View(); 
}
除了View()之外那我們這裡還能用於返回什麼值呢?

一、ascx頁面

情境:要傳回碼片斷,比如Ajax返回一個子頁

我們先建立一個Action

public ActionResult Ascx() 
{ 
return PartialView(); 
}
我們下面再建一個View,仍然是在Action中點右鍵,AddView。

注意圖中勾選。

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

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <div> 得到一個DIV </div>
運行,得到頁面


二、返迴文本

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

此時我們可以使用以下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"//檔案類型
); 
}

MVC Controller return 格式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.