標籤:
所看到的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 格式