4

在 EPiServer CMS 7 中,可以使用一个或多个标签来标记内容区域:

@Html.PropertyFor(x => x.CurrentPage.MainContent, new { Tag = "ContentTag" })

您可以连接页面类型和标签以创建具有TemplateDescriptor属性的控制器的一种方法:

[TemplateDescriptor(
    TemplateTypeCategory = TemplateTypeCategories.MvcPartialController,
    Default = true,
    Tags = new[] { "ContentTag", "SecondTag" }
    )]
public class SitePageDataController : PageController<SitePageData>
{
    public ActionResult Index(SitePageData currentContent)
    {
        return View(currentContent);
    }
}

在上面的示例中,可能由于两个标签而选择了 SitePageDataController。有什么方法可以在运行时找出导致选择当前控制器的标签?

他们是我可以在我的控制器操作中调用的 API 来获取标签吗?

4

2 回答 2

2

我知道这个问题是两年前提出的,但有办法。简短的回答是写

var tag = ControllerContext.ParentActionViewContext.ViewData["tag"] as string;

(可以为空)

在你里面行动。这篇博客文章更详细地描述了它http://world.episerver.com/blogs/Anders-Hattestad/Dates/2014/3/EPiServer-7-and-MVC-Views-using-Tags/

于 2015-09-11T13:42:03.993 回答
1

据我所见,标签值并未与请求一起发送到部分控制器,因此无法立即找到标签。

一种解决方法是挂钩在管道中调用的 TemplateResolved 事件,并将标记名称添加到路由值。这样,您只需向名为“tag”的操作添加一个参数,它将使用当前标签填充。

[InitializableModule]
[ModuleDependency(typeof(InitializationModule))]
public class SiteInitializer : IInitializableModule {

    public void Initialize(InitializationEngine context) {   
        var templateResolver = ServiceLocator.Current.GetInstance<TemplateResolver>();
        templateResolver.TemplateResolved += OnTemplateResolved;
    }

    private void OnTemplateResolved(object sender, TemplateResolverEventArgs templateArgs) {
        var routeData = templateArgs.WebContext.Request.RequestContext.RouteData;

        if (!string.IsNullOrEmpty(templateArgs.Tag) && templateArgs.SelectedTemplate != null) {
            // add the tag value to route data. this will be sent along in the child action request. 
            routeData.Values["tag"] = templateArgs.Tag;
        }
        else {
            // reset the value so that it doesn't conflict with other requests.
            routeData.Values["tag"] = null;
        }
    }

    public void Uninitialize(InitializationEngine context) { }
    public void Preload(string[] parameters) { }
}

如果您将其用于其他用途,您可能希望选择与“标签”不同的名称。

在您的控制器操作中,只需添加一个标记参数:

public ActionResult Index(PageData currentPage, string tag) {
    if (!string.IsNullOrEmpty(tag)) {
        return PartialView(tag, currentPage);
    }

    return PartialView(currentPage);
}
于 2013-11-10T10:57:10.497 回答