我有一个模板BrochuresComponent,它有一个名为Location的字段,它是一个droptree。现在,在sitecore模板中的字段上使用source,用户只能在此下拉选项中添加国家/地区项目或大陆项目。我希望玻璃将选项中的国家/地区项目映射到ICountry玻璃项目,将大陆项目映射到Icontinent玻璃项目。
但是当用户在下拉列表中选择一个选项时,会填充其中一个glassItem值,而其他值则会在其上显示评估错误,从而导致模型出错。以下是我的代码段。
我的玻璃界面如下所示:
using Collette.Library.GlassItems.Objects.Taxonomy.Locations;
using Collette.Library.GlassItemsConstants.Objects.Page_Components.Destination_Page_Components;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.Configuration.Attributes;
namespace Collette.Library.GlassItems.Objects.Page_Components.Destination_Page_Components
{
[SitecoreType(TemplateId = BrochureComponentsConstants.TemplateIdString, AutoMap = true)]
public interface IBrochuresComponent: IGlassItemEx
{
//Brochures Data Section
[SitecoreField(FieldType = SitecoreFieldType.DropTree, FieldId = BrochureComponentsConstants.LocationItemFieldId, Setting = SitecoreFieldSettings.InferType)]
ICountry Country { get; set; }
[SitecoreField(FieldType = SitecoreFieldType.DropTree, FieldId = BrochureComponentsConstants.LocationItemFieldId, Setting = SitecoreFieldSettings.InferType)]
IContinent Continent { get; set; }
}
}
我的模型如下:
var sitecoreContext = new SitecoreContext();
BrochuresComponentItem = sitecoreContext.Cast<IBrochuresComponent>(DisplayItem);
//IF we specified a continent in dropdown it works fine since that is the first condition so it does not go to else,
//but if we specify a country in the dropdown it breaks at the if condition below stating that templateid is empty string since nothing was evaluated.
不允许使用空字符串。 参数名称:fieldName
if (BrochuresComponentItem.Continent != null && BrochuresComponentItem.Continent.TemplateId.Equals(ContinentConstants.TemplateId))
{
SetBrochures(BrochuresComponentItem.Continent);
}
else if (BrochuresComponentItem.Country != null && BrochuresComponentItem.Country.TemplateId.Equals(CountryConstants.TemplateId))
{
SetBrochures(BrochuresComponentItem.Country);
}
答案 0 :(得分:3)
您对incrtype工作方式的实施/理解是错误的,请阅读Glass tutorial for Inferred Types。
为了使其正常工作,您的Country和Continent模板需要有一个共同的基础,然后您可以使用incrtype映射到特定类型:
[SitecoreType(TemplateId = BrochureComponentsConstants.TemplateIdString, AutoMap = true)]
public interface IBrochuresComponent: IGlassItemEx
{
//Brochures Data Section
[SitecoreField(FieldType = SitecoreFieldType.DropTree, FieldId = BrochureComponentsConstants.LocationItemFieldId, Setting = SitecoreFieldSettings.InferType)]
ILocationBase Location { get; set; }
}
然后在您的代码上,您可以检查它已映射到的类型:
if (BrochuresComponentItem.Location != null)
{
if (BrochuresComponentItem.Location is ICountry)
{
//do country specific thing
}
else if (BrochuresComponentItem.Location is IContinent)
{
// do continent specific thing
}
}
确保ICountry
和IContinent
的模型都从公共基接口继承,以匹配基础数据模板ILocationBase