最近,当我构建我的 ASP.NET MVC 应用程序时,我倾向于在我的母版页中始终需要计算、格式化和配置许多项目。其中一些项目包括:
- 我喜欢将特定的类附加到 body 标记,就像 WordPress 那样来帮助我的 CSS 解决问题。我通常会附上操作的名称、控制器、页面模板等。
- 我喜欢在我的母版页中使用自定义 IIdentity。这个IIdentity包括用户的nice Display Name、UserID、UserName等。
- 等等...取决于项目
我实现这一目标的方式也发生了变化。我首先发送 ViewData 以及每个操作结果来填充母版页中的内容。示例->
// in the action
ViewData["BodyClasses"] = "index home default";
ViewData["UserData"] = userData;
return View();
// in the master page
<% UserData userData = (UserData)ViewData["UserData"] %>
...
<body class="<%= (string)ViewData["BodyClasses"] %>">
那太可怕了。因此,我开始在母版页的顶部放置一些变量,并根据我们必须在母版页中使用的对象填充它们。示例->
<%@ Master Language="C#" Inherits="System.Web.MVC.ViewMasterPage" %>
<% string controller = ViewContext.RouteData.Values["controller"].ToString().ToLower();
string action = ViewContext.RouteData.Values["action"].ToString().ToLower();
CustomIdentity identity = (CustomIdentity)User.Identity %>
...
<body class="no-js <%= controller + " " + action %>">
这更好,但我觉得必须有一个更简单的解决方案。我开始尝试创建自定义 ViewMasterPage 并添加一些公共属性。是否有其他人在母版页上执行此操作,或者是否有其他我完全缺少的解决方案?
我只使用常规内容占位符来表示正文标记 ID 和类。
<body id="<asp:ContentPlaceHolder ID="BodyTagId" runat="server" />">
然后在引用母版页的给定页面中使用它:
<asp:Content ContentPlaceHolderID="BodyTagId" runat="server">about-page</asp:Content>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)