【问题标题】:how to populate partial view for display on every page如何填充部分视图以在每个页面上显示
【发布时间】:2011-05-16 17:14:15
【问题描述】:

这可能是一个愚蠢的问题,但我试图弄清楚如何为显示登录用户 DisplayName 的局部视图填充 ViewModel。此部分视图位于主布局中,因此它将出现在每个页面上。我知道听起来很简单;但是对于我的一生,我无法找出将数据获取到视图的最佳方法。我如何坚持这种观点?

【问题讨论】:

  • 局部视图是强类型的吗?
  • 是的,它有 @model Web.ViewModels.LoggedInUserParttailViewModel
  • 试图弄清楚何时何地使用 viewModel 将数据获取到部分
  • 看看这一切,伙计们。你们非常感谢您的快速回复。

标签: model-view-controller asp.net-mvc-3


【解决方案1】:

最好的方法可能是使用子操作和Html.Action helper

因此,在 ASP.NET MVC 中,您始终从一个视图模型开始,该模型将表示您愿意在视图中操作/显示的信息:

public class UserViewModel
{
    public string FullName { get; set; }
}

然后是控制器:

public class UsersController: Controller
{
    // TODO: usual constructor injection here for
    // a repository, etc, ..., omitted for simplicity

    public ActionResult Index()
    {
        var name = string.Empty;
        if (User.Identity.IsAuthenticated)
        {
            name = _repository.GetFullName(User.Identity.Name);
        }
        var model = new UserViewModel
        {
            FullName = name
        };
        return PartialView(model);
    }
}

对应的局部视图:

@model UserViewModel
{
    // Just to make sure that someone doesn't modify
    // the controller code and returns a View instead of
    // a PartialView in the action because in this case
    // a StackOverflowException will be thrown (if the child action
    // is part of the layout)
    Layout = null; 
}
<div>Hello @Model.FullName</div>

然后在您的 _Layout 中继续并包含此操作:

@Html.Action("Index", "Users")

显然,此代码的下一个改进是避免在每次请求时访问数据库,而是在用户登录后将此信息存储在某处,因为它会出现在所有页面上。例如,加密身份验证 cookie 的 userData 部分(当然,如果您使用 FormsAuthentication)、Session、...

【讨论】:

  • 所以局部视图的名称必须与ActionResult的名称相同?
  • @Assistant 到助手,是的,通常的 ASP.NET MVC 约定。它应该位于~/Views/Users/Index.cshtml 文件夹中。 Users 因为这是我在示例中使用的控制器的名称,Index 因为这是我在示例中使用的操作的名称。
  • 我明白了。我使用推荐的局部视图命名,以 _ 开头,例如 _LoggedInUserPartial.cshtml,它位于 View/Shared 文件夹中。
  • public ActionResult _LoggedInUserPartial() { var model = new ViewModels.LoggedInUserParttailViewModel(); model.DisplayName = _profileService.GetDisplayNameFromProfile(User.Identity.Name);返回部分视图(模型);这很好。
【解决方案2】:

您可以考虑使用子操作方法。

【讨论】:

    猜你喜欢
    • 2020-02-22
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多