编辑ASP.NET MVC认证模板时,为_LoginPartial.cshtml创建ViewModel的疑问
嘿,我来帮你搞定这个问题!其实创建ViewModel确实是个挺不错的方案,能让你的视图和业务逻辑彻底解耦,代码也更干净易维护。咱们一步步来操作:
第一步:创建LoginPartialViewModel
先在你的Models文件夹下新建这个ViewModel类,专门用来给登录局部视图传数据:
public class LoginPartialViewModel { // 你要显示的用户名(或者真实姓名,根据你的用户表字段调整) public string DisplayName { get; set; } // 标记用户是否已登录 public bool IsAuthenticated { get; set; } }
第二步:在控制器里填充ViewModel
推荐用**子动作(Child Action)**来处理这个局部视图的数据,这样不用每个页面的控制器都重复写逻辑。比如在HomeController里加这么个方法:
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using YourProjectName.Models; // 替换成你的项目命名空间 public class HomeController : Controller { // 其他原有Action... [ChildActionOnly] // 这个标记确保该Action只能被局部视图调用 public ActionResult LoginPartial() { var viewModel = new LoginPartialViewModel(); if (User.Identity.IsAuthenticated) { // 获取当前登录用户的信息 var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var currentUser = userManager.FindById(User.Identity.GetUserId()); // 这里替换成你要显示的字段,比如UserName、FullName等等 viewModel.DisplayName = currentUser.UserName; viewModel.IsAuthenticated = true; } else { viewModel.IsAuthenticated = false; } return PartialView("_LoginPartial", viewModel); } }
第三步:修改_LoginPartial.cshtml视图
把视图改成强类型绑定到咱们的ViewModel,彻底把逻辑从视图里剥离:
@model YourProjectName.Models.LoginPartialViewModel @if (Model.IsAuthenticated) { <div class="navbar-text"> Hello, <strong>@Model.DisplayName</strong>! @Html.ActionLink("Log Off", "LogOff", "Account", null, new { @class = "navbar-link" }) </div> } else { @Html.ActionLink("Register", "Register", "Account", null, new { @class = "navbar-link" }) @Html.ActionLink("Log In", "Login", "Account", null, new { @class = "navbar-link" }) }
第四步:更新_Layout.cshtml里的调用
原来你可能直接用@Html.Partial("_LoginPartial"),现在改成调用咱们的子动作:
@Html.Action("LoginPartial", "Home")
额外说明:不用ViewModel行不行?
其实也可以直接在视图里获取用户信息,但这样会把业务逻辑混在视图里,后期不好维护。比如直接在_LoginPartial里写:
@if (User.Identity.IsAuthenticated) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var user = userManager.FindById(User.Identity.GetUserId()); <text>Hello, @user.UserName!</text> }
但显然ViewModel的方式更符合MVC的设计理念,代码也更清晰、更易扩展。
内容的提问来源于stack exchange,提问作者Leonardo Henriques
相关产品推荐
相关产品推荐

