2013-01-23 38 views
2

訪問數據我有一個這樣的控制器:你總是必須設置ViewBag變量以便從控制器

 public ActionResult Index() 
     { 
      ViewBag.Title = "Index"; 
      ViewBag.LoggedIn = TheUser.CheckStatus(); 

      return View(); 
     } 

事情是,我要的loggedIn設置爲我的其他功能TheUser的輸出。 CheckStatus(),以便我可以用剃刀來引用它...... Razor有沒有辦法直接訪問函數?例如...

@TheUser.CheckStatus 

代替

@ViewBag.LoggedIn 
+1

使用「ViewModel」類而不是ViewBag。 –

+0

.NET新手,它們是什麼?我可以有一些語法示例:D – Jimmyt1988

回答

5

MVC中推薦的將信息傳遞給視圖的方法是創建特定於該視圖的模型(也稱爲視圖模型),例如,

public class IndexViewModel 
{ 
    public string Title { get; set; } 
    public bool IsAuthenticated { get; set; } 
} 
.... 
public ActionResult Index() 
{ 
    return View(new IndexViewModel() 
    { 
     Title = "Index", 
     IsAuthenticated = UserIsLoggedIn() 
    }); 
} 

然而,要回答你的問題:

是否有剃刀的方式來訪問功能直客?

如果您使用的是ASP.NET Membership,則可以在請求中使用IsAuthenticated屬性,例如,

@Request.IsAuthenticated 

否則,你就需要把這個信息傳遞給視圖(不管是通過ViewBag /視圖模型等)

或者,你可以寫爲Request自己的擴展方法,這樣可以讓你直接訪問它的觀點:

@Request.UserLoggedIn() 

甚至作爲HtmlHelper

public static class HtmlHelperExtensions 
{ 
    public static bool UserIsLoggedIn(this HtmlHelper helper) 
    { 
     return /* authentication code here */ 
    } 
} 

然後在你的觀點,你可以使用@Html.UserIsLoggedIn()認爲是你所追求的。

4

使用ViewModel類(你的觀點將被強類型的,你就可以用「經典」的傭工)。

//viewModel class 
public class UserStatusViewModel { 
    public string Title {get;set;} 
    public bool IsLogged {get;set; 
} 


//action 
public ActionResult Index() { 
    var model = new UserStatusViewModel{ Title = "Index", IsLogged = TheUser.CheckStatus()}; 
    return View(model); 
} 

//view 

@model UserStatusViewModel 

@Html.DisplayFor(m => m.Title) 
@Html.DisplayFor(m => m.IsLoggedIn)