我收到了开发人员的回复,说这是由于 ASP.NET 的限制。他希望通过完全分离此功能来在版本 4 中删除此功能。在此之前,最好的解决方案是通过将标题作为 ViewData 传递来覆盖标题。
编辑(以下是我想出的临时解决方案):
创建以下 SiteMapAttribute.cs 文件:
public class SiteMapAttribute : ActionFilterAttribute {
protected string TitlePropertyName { get; set; }
protected string PageTitlePropertyName { get; set; }
protected string MetaDescriptionPropertyName { get; set; }
protected string MetaKeywordsPropertyName { get; set; }
protected string ParentTitlePropertyName { get; set; }
public SiteMapAttribute() {
}
public SiteMapAttribute(string titlePropertyName) {
TitlePropertyName = titlePropertyName;
}
public SiteMapAttribute(string titlePropertyName, string pageTitlePropertyName, string metaDescriptionPropertyName, string metaKeywordsPropertyName)
: this(titlePropertyName) {
PageTitlePropertyName = pageTitlePropertyName;
MetaDescriptionPropertyName = metaDescriptionPropertyName;
MetaKeywordsPropertyName = metaKeywordsPropertyName;
}
public SiteMapAttribute(string titlePropertyName, string pageTitlePropertyName, string metaDescriptionPropertyName, string metaKeywordsPropertyName, string parentTitlePropertyName)
: this(titlePropertyName, pageTitlePropertyName, metaDescriptionPropertyName, metaKeywordsPropertyName) {
ParentTitlePropertyName = parentTitlePropertyName;
}
public override void OnActionExecuted(ActionExecutedContext filterContext) {
if (filterContext.Result is ViewResult) {
var result = (ViewResult)filterContext.Result;
// Get the current node
var currentNode = filterContext.Controller.GetCurrentSiteMapNode();
// Make sure the node is found
if (currentNode != null) {
// Set the title and meta information (if applicable)
if (!result.ViewData.ContainsKey("Title"))
result.ViewData["Title"] = Resolve(result, TitlePropertyName) ?? currentNode.Title;
if (!result.ViewData.ContainsKey("PageTitle"))
result.ViewData["PageTitle"] = Resolve(result, PageTitlePropertyName) ?? (currentNode["PageTitle"] ?? currentNode.Title);
if (!result.ViewData.ContainsKey("MetaDescription"))
result.ViewData["MetaDescription"] = Resolve(result, MetaDescriptionPropertyName) ?? currentNode["MetaDescription"];
if (!result.ViewData.ContainsKey("MetaKeywords"))
result.ViewData["MetaKeywords"] = Resolve(result, MetaKeywordsPropertyName) ?? currentNode["MetaKeywords"];
if (!result.ViewData.ContainsKey("ParentTitle"))
result.ViewData["ParentTitle"] = Resolve(result, ParentTitlePropertyName);
}
}
}
private string Resolve(ViewResult result, string propertyName) {
if (string.IsNullOrEmpty(propertyName))
return null;
var target = ResolveTarget(result.ViewData.Model, propertyName);
if (target == null)
target = ResolveTarget(result.ViewData, propertyName);
return target != null ? target.ToString() : null;
}
private object ResolveTarget(object target, string expression) {
try {
var parameter = Expression.Parameter(target.GetType(), "target");
var lambdaExpression = DynamicExpression.ParseLambda(new[] { parameter }, null, "target." + expression);
return lambdaExpression.Compile().DynamicInvoke(target);
} catch {
return null;
}
}
}
然后,您需要确保所有控制器都应用了此属性。在 ASP.NET MVC 3 中,这要简单得多,因为您可以将其注册为全局过滤器。
现在您需要修改您的母版页并说如下内容:
<head>
<title><%= ViewData["PageTitle"] %></title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<% if (ViewData["MetaDescription"] != null && !string.IsNullOrEmpty(ViewData["MetaDescription"].ToString())) { %>
<meta name="Description" content="<%= ViewData["MetaDescription"] %>" />
<% } %>
<% if (ViewData["MetaKeywords"] != null && !string.IsNullOrEmpty(ViewData["MetaKeywords"].ToString())) { %>
<meta name="Keywords" content="<%= ViewData["MetaKeywords"] %>" />
<% } %>
</head>
现在要修补面包屑(SiteMapPath),我不得不有点hacky。首先我创建了自己的助手:
/// <summary>
/// MvcSiteMapHtmlHelper extension methods
/// </summary>
public static class SiteMapBreadcrumbExtensions {
/// <summary>
/// Source metadata
/// </summary>
private static Dictionary<string, object> SourceMetadata = new Dictionary<string, object> { { "HtmlHelper", typeof(SiteMapBreadcrumbExtensions).FullName } };
/// <summary>
/// Gets SiteMap path for the current request
/// </summary>
/// <param name="helper">MvcSiteMapHtmlHelper instance</param>
/// <returns>SiteMap path for the current request</returns>
public static MvcHtmlString SiteMapBreadcrumb(this MvcSiteMapHtmlHelper helper) {
return SiteMapBreadcrumb(helper, null);
}
/// <summary>
/// Gets SiteMap path for the current request
/// </summary>
/// <param name="helper">MvcSiteMapHtmlHelper instance</param>
/// <param name="templateName">Name of the template.</param>
/// <returns>SiteMap path for the current request</returns>
public static MvcHtmlString SiteMapBreadcrumb(this MvcSiteMapHtmlHelper helper, string templateName) {
var model = BuildModel(helper, helper.Provider.CurrentNode);
return helper
.CreateHtmlHelperForModel(model)
.DisplayFor(m => model, templateName, new { Title = helper.HtmlHelper.ViewData["Title"], ParentTitle = helper.HtmlHelper.ViewData["ParentTitle"], ParentUrl = helper.HtmlHelper.ViewData["ParentUrl"] });
}
/// <summary>
/// Builds the model.
/// </summary>
/// <param name="helper">The helper.</param>
/// <param name="startingNode">The starting node.</param>
/// <returns>The model.</returns>
private static SiteMapPathHelperModel BuildModel(MvcSiteMapHtmlHelper helper, SiteMapNode startingNode) {
// Build model
var model = new SiteMapPathHelperModel();
var node = startingNode;
while (node != null) {
var mvcNode = node as MvcSiteMapNode;
// Check visibility
var nodeVisible = true;
if (mvcNode != null)
nodeVisible = mvcNode.VisibilityProvider.IsVisible(node, HttpContext.Current, SourceMetadata);
// Check ACL
if (nodeVisible && node.IsAccessibleToUser(HttpContext.Current))
model.Nodes.Add(SiteMapNodeModelMapper.MapToSiteMapNodeModel(node, mvcNode, SourceMetadata));
node = node.ParentNode;
}
model.Nodes.Reverse();
return model;
}
}
这和内置的唯一区别是它将 ViewData 传递给模板。最后我创建了 2 个显示模板:
SiteMapNodeModel.axcx:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcSiteMapProvider.Web.Html.Models.SiteMapNodeModel>" %>
<% if (Model.IsCurrentNode) { %>
<span class="orange-text"><%= (ViewData["Title"] ?? Model.Title).ToString() %></span>
<% } else if ((bool)ViewData["IsParent"]) { %>
<a href="<%= (ViewData["ParentUrl"] ?? Model.Url).ToString() %>"><%= (ViewData["ParentTitle"] ?? Model.Title).ToString() %></a>
<% } else { %>
<a href="<%= Model.Url %>"><%= Model.Title %></a>
<% } %>
和 SiteMapPathHelperModel.ascx:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcSiteMapProvider.Web.Html.Models.SiteMapPathHelperModel>" %>
<% for (var i = 0; i < Model.Nodes.Count(); i++) { %>
<%= Html.DisplayFor(m => Model.Nodes[i], new { isParent = Model.Count() - 2 == i }) %>
<% if (Model.Nodes[i] != Model.Last()) { %>
>
<% } %>
<% } %>
您现在可以在视图中说以下内容来显示覆盖的面包屑:
<%= Html.MvcSiteMap().SiteMapBreadcrumb() %>
现在完成后,您只需要知道如何覆盖特定操作的元/面包屑信息。最简单的方法是覆盖特定操作的 SiteMapAttribute,例如
[SiteMap("Subject", "Subject", "Subject", "", "Forum.ForumName")]
public ActionResult ViewTopic(int id, [DefaultValue(1)] int page) {
}
这将相应地设置标题、页面标题、元信息和父标题。如果您希望将标题绑定到比单个属性更复杂的东西,您可以在 action 方法中设置它,方法是:
ViewData["Title"] = "My Title - " + DateTime.UtcNow.ToShortDateString();
希望这可以帮助。