ASP.NET MVC-ActionResult

  • 450
  • 0

寫程式也一段時間,一直沒去搞懂一些東西

認真下定決心要去弄懂一些基礎知識

如有說錯也可以糾正<(-_-)>

在Controller中每一個Action都要回傳一個ActionResult型別的物件

接著再把結果丟回給瀏覽器呈現給使用者看,以下介紹幾種繼承ActionResult型別物件

1.ContentResult

回傳字串的方法,他有三個方法可以使用

其中加上Content-type,可以針對要回傳的文字,做不同的輸出,Xml、或是csv

//回傳純文字
public ActionResult ContentMethod1()
{
   return Content("Hello ASP.net MVC");
}

//指定Content-type回傳html
public ActionResult ContentMethod2()
{
  return Content("<h1>Hello ASP.net MVC</h1>","text/html");
}

//還可以加上編碼格式
public ActionResult ContentMethod3()
{
   return Content("<h1>Hello ASP.net MVC</h1>", "text/csv",Encoding.UTF8);
}

2.JsonResult

回傳json字串

//允許allowget會有資安風險,建議不要這樣做
public ActionResult JsonMethod1()
{
   return Json(new { Name = "123", Id = 123 },JsonRequestBehavior.AllowGet);
}

3.FilePathResult

可以透過瀏覽器下載檔案

第二個參數設定Content-Type

第三個參數可以設定要下載的檔案名稱

//可以設定要下載的檔案,並設定content-type
public ActionResult FileResult()
{
    string path = Server.MapPath(@"~\Content\Site.css");
    return File(path, "application-octet-stream");
}
//如果要指定檔案案名稱,可以設定第三個參數
public ActionResult FileResult()
{
    string path = Server.MapPath(@"~\Content\Site.css");
    return File(path, "application-octet-stream","123.css");
}