Umbraco 的template使用的默认Model问题

Umbraco中的Template默认都继承自 Umbraco.Web.Mvc.UmbracoTemplatePage

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage

它使用了默认的model => Umbraco.Web.Models.RenderModel.

但是,如果你的这个template需要使用一个Custom model, 怎么办。

方法是,使用如下继承指令

@inherits Umbraco.Web.Mvc.UmbracoViewPage<MyCustomModel>

 但是,我们通常的做法是项目中有一个Layout模板(Layout template),项目中其他所有的模板(template)都继承自这个layout模板。 那么如果Layout模板使用的是继承自UmbracoTemplatePage (@inherits Umbraco.Web.Mvc.UmbracoTemplatePage)

,Layout模板默认的model就是RenderModel. 这种情况就会产生冲突,导致exception发生。因为我们的template继承自layout模板,但使用的确是MyCustomModle (@inherits Umbraco.Web.Mvc.UmbracoViewPage<MyCustomModel>)

解决这个问题,有两种方法

方法一:

改变Layout模板中的继承,现在Layout模板是@inherits Umbraco.Web.Mvc.UmbracoTemplatePage,改为继承自 Umbraco.Web.Mvc.UmbracoViewPage<dynamic>,这意味着对应的Model将会是dynamic这个类型,而不再是Umbraco.Web.Models.RenderModel

@inherits Umbraco.Web.Mvc.UmbracoViewPage<dynamic>

这样的话,我们的template继承自layout模板,并且使用@inherits Umbraco.Web.Mvc.UmbracoViewPage<MyCustomModel>, 就没有问题了

方法二

不改变Layout模板中的模板继承类型,也就是说还是@inherits Umbraco.Web.Mvc.UmbracoTemplatePage

但是改变我们模板中使用的MyCustomModel,让它继承自Umbraco.Web.Models.RenderModel

public class MyCustomModel : RenderModel
{
    //Standard Model Pass Through
    public MyCustomModel(IPublishedContent content) : base(content) { }

    //Custom properties here...
    public string MyProperty1 { get; set; }
    public string MyProperty2 { get; set; }
}

具体可参考 https://our.umbraco.org/documentation/Reference/Routing/custom-controllers

原文地址:https://www.cnblogs.com/wphl-27/p/7684879.html