c# - 您是否总是必须设置 ViewBag 变量才能从 Controller 访问数据

标签 c# .net razor viewbag

我有一个这样的 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/

相关文章:

c# - MVC4 局部 View 错误 "Object reference not set to an instance of an object."

javascript - Razor页面javascript仅执行c#一次

c# - 将 Excel 模板保存为资源的一部分 C# Visual Studio

.net - 将数据访问策略切换到项目中?

c# - C# 中的类修饰符问题与 "private"类

.net - ReportViewer 控件加载指示器?

c# - 使用动态类型作为它自己的基类型的参数

c# - 在 Blazor 中,如何在动态模型中 @bind 然后触发 @onchange

c# - 如何确定母版页显示的是哪个子页?

c# - 为什么 .NET MVC 4 从 GET 查询字符串而不是模型联编程序中获取值