我有以下要求.我已经存储了一个字典项列表.我希望Dictionary Key是唯一的.我编写了以下代码,就像任何新项目使用现有密钥名称保存一样,它应该抛出类似“项已存在”的警报.
我正在做的是在保存项目时将Key值与现有字典键进行比较.我已经在ItemSaving事件中编写了代码.
public class IsItemExist { Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master"); public void OnItemSaving(object sender,EventArgs args) { Item dbItem = master.GetItem("/sitecore/content/Administration/Development Settings/Lookups"); Item selectedItem = Event.ExtractParameter(args,0) as Item; foreach (Item item in dbItem.Axes.GetDescendants()) { if (item.Template.Name.Contains("entry")) { if (item.Fields["Key"].Value == selectedItem.Fields["Key"].Value) { Sitecore.Context.ClientPage.ClientResponse.Alert("Item is already exist"); } } } } }
web.config条目
<event name="item:saving"> <handler type="CustomEvent.IsItemExist,CustomEvent" method="OnItemSaving"/> </event>
它显示警报消息,我可以保存该项目.
1.我不想再次使用重复值保存项目.
点击保存按钮后,我得到2个警报信息.为什么?
任何帮助将不胜感激.谢谢各位…
解决方法
您应该将处理程序添加到item:添加事件并将事件结果的Cancel属性设置为true:
<event name="item:adding"> <handler type="CustomEvent.DoesItemExist,CustomEvent" method="OnItemAdding" /> </event>
public class DoesItemExist { Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master"); public void OnItemAdding(object sender,EventArgs args) { Item dbItem = master.GetItem("/sitecore/content/Administration/Development Settings/Lookups"); Item selectedItem = Event.ExtractParameter(args,0) as Item; foreach (Item item in dbItem.Axes.GetDescendants()) { if (item.Template.Name.Contains("entry")) { if (item.Fields["Key"].Value == selectedItem.Fields["Key"].Value) { SitecoreEventArgs evt = args as SitecoreEventArgs; evt.Result.Cancel = true; Sitecore.Context.ClientPage.ClientResponse.Alert("Item already exists"); } } } } }