1. 程式人生 > >Asp.net mvc中Controller的返回值

Asp.net mvc中Controller的返回值

(1)EmptyResult:當用戶有誤操作或者是圖片防盜鏈的時候,這個EmptyResult就可以派上用場,返回它可以讓使用者啥也看不到內容,通過訪問瀏覽器端的原始碼,發現是一個空內容;

public ActionResult EmptyResult()  
{  
    //空結果當然是空白了!  
    //至於你信不信, 我反正信了  
    return new EmptyResult();  
}

(2)Content:通過Content可以向瀏覽器返回一段字串型別的文字結果,就相當於Response.Write("xxxx");一樣的效果;

public ActionResult ContentResult()  
{  
    
return Content("Hi, 我是ContentResult結果"); }

3)File:通過File可以向瀏覽器返回一段檔案流,主要用於輸出一些圖片或檔案提供下載等;

public ActionResult FileResult()  
{  
    var imgPath = Server.MapPath("~/demo.jpg");  
    return File(imgPath, "application/x-jpg", "demo.jpg");  
} 

(4)HttpUnauthorizedResult:通過HttpUnauthorizedResult可以向瀏覽器輸出指定的狀態碼和狀態提示,如果不指定狀態碼,則預設為401無權訪問;

public ActionResult HttpUnauthorizedResult()  
{  
    //未驗證時,跳轉到Logon  
    return new HttpUnauthorizedResult();  
} 

(5)Redirect與RedirectToAction:重定向與重定向到指定Action,我一般使用後者,主要是向瀏覽器傳送HTTP 302的重定向響應;

public ActionResult RedirectToRouteResult()  
{  
    return RedirectToRoute(new {  
        controller 
= "Hello", action = "" }); }

(6)JsonResult:通過Json可以輕鬆地將我們所需要返回的資料封裝成為Json格式

  1.返回list

var res = new JsonResult();  
           //var value = "actionValue";  
           //db.ContextOptions.ProxyCreationEnabled = false;  
           var list = (from a in db.Articles  
                       select new  
                       {  
                           name = a.ArtTitle,  
                           yy = a.ArtPublishTime  
                       }).Take(5);  
           //記得這裡要select new 否則會報錯:序列化型別 System.Data.Entity.DynamicProxies XXXXX 的物件時檢測到迴圈引用。  
           //不select new 也行的加上這句 //db.ContextOptions.ProxyCreationEnabled = false;  
           res.Data = list;//返回列表

  2.返回單個物件

var person = new { Name = "小明", Age = 22, Sex = "" }; 
          res.Data = person;//返回單個物件;

  3直接返回單個物件

     public JsonResult GetPersonInfo()
        {
            var person = new
            {
                Name = "張三",
                Age = 22,
                Sex = ""
            };
            return Json(person,JsonRequestBehavior.AllowGet);
        }

res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允許使用GET方式獲取,否則用GET獲取是會報錯。

(7)JavaScript:可以通過JavaScriptResult向瀏覽器單獨輸出一段JS程式碼,不過由於主流瀏覽器都對此進行了安全檢查,因此你的JS程式碼也許無法正常執行,反而是會以字串的形式顯示在頁面中;

public ActionResult JavaScriptResult()  
{  
    string js = "alert(\"Hi, I'm JavaScript.\");";  
    return JavaScript(js);  
}  

(8)ActionResult  預設的返回值型別,通常返回一個View物件

[ChildActionOnly]  
public ActionResult ChildAction()  
{  
    return PartialView();  
}  

(9)HttpNotFoundResult

public ActionResult HttpNotFoundResult()  
{  
    return HttpNotFound("Page Not Found");  
}