我有一个这样的 Controller :
public ActionResult Index()
{
ViewBag.Title = "Index";
ViewBag.LoggedIn = TheUser.CheckStatus();
return View();
}
问题是,我必须将 LoggedIn 设置为我的其他函数 TheUser.CheckStatus() 的输出,以便我可以使用 razor 引用它...Razor 中是否有直接访问函数的方法?例如……
@TheUser.CheckStatus
代替
@ViewBag.LoggedIn
最佳答案
在 MVC 中向 View 传递信息的推荐方法是创建一个特定于该 View 的模型(也称为 View 模型),例如
public class IndexViewModel
{
public string Title { get; set; }
public bool IsAuthenticated { get; set; }
}
....
public ActionResult Index()
{
return View(new IndexViewModel()
{
Title = "Index",
IsAuthenticated = UserIsLoggedIn()
});
}
但是,要回答您的问题:
Is there a way in Razor to access a function straight off?
如果您使用的是 ASP.NET 成员资格,则可以使用 IsAuthenticated请求的属性,例如
@Request.IsAuthenticated
否则,您确实需要将此信息传递给 View (无论是通过 ViewBag
/view model 等)
或者,您可以为 Request
编写自己的扩展方法,这将允许您直接在 View 中访问它:
@Request.UserLoggedIn()
或者甚至作为 HtmlHelper
例如
public static class HtmlHelperExtensions
{
public static bool UserIsLoggedIn(this HtmlHelper helper)
{
return /* authentication code here */
}
}
然后在您的 View 中,您可以使用 @Html.UserIsLoggedIn()
,我认为就是您所追求的。
关于c# - 您是否总是必须设置 ViewBag 变量才能从 Controller 访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14482925/