通过前面几篇,我们已经完成了内容类型,列表定义,列表实例的开发。本篇继续讲解列表中的一个重要环节——事件接收器开发。
我们的场景是:我希望之前做好的订单列表这个内容类型自动地具有某些事件特征,例如当用户在添加一个条目的时候,检查订购日期,如果小于今天的话,就不让添加。(这只是一个假设的场景,现实工作中可以依照业务逻辑而定)
我们应该如何实现这个需求呢?Follow me
1.添加一个事件接收器
下面是默认生成的两个文件
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Receivers ListTemplateId="10000">
<Receiver>
<Name>OrderItemEventReceiverItemAdding</Name>
<Type>ItemAdding</Type>
<Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
<Class>OrderListSolution.OrderItemEventReceiver.OrderItemEventReceiver</Class>
<SequenceNumber>10000</SequenceNumber>
</Receiver>
</Receivers>
</Elements>
2. 修改有关代码实现业务逻辑
using System; using System.Security.Permissions; using Microsoft.SharePoint; using Microsoft.SharePoint.Security; using Microsoft.SharePoint.Utilities; using Microsoft.SharePoint.Workflow; namespace OrderListSolution.OrderItemEventReceiver { /// <summary> /// List Item Events /// </summary> public class OrderItemEventReceiver : SPItemEventReceiver { /// <summary> /// An item is being added. /// </summary> public override void ItemAdding(SPItemEventProperties properties) { SPItemEventDataCollection data = properties.AfterProperties; SPList list = properties.OpenWeb().Lists[properties.ListId]; string fieldName= list.Fields.GetField("订购日").InternalName; var date = DateTime.Parse(data[fieldName].ToString()); if (date > DateTime.Now) { properties.ErrorMessage = "当前添加的日期不合法"; properties.Cancel = true; return; } } } }
3.部署和调试,按下F5键
【注意】我们这里故意将订购日设置于大于当前日期。根据事件中的逻辑,我们预期它会报告一个错误,而且取消当前的提交
我们看到了这个错误页面,看起来有些吓人,不是吗?对于一般用户来说,他们可能要被吓坏了
接下来,我们可以定义一个专门的页面来显示错误消息,提高用户体验
然后修改一下代码
using System; using System.Security.Permissions; using Microsoft.SharePoint; using Microsoft.SharePoint.Security; using Microsoft.SharePoint.Utilities; using Microsoft.SharePoint.Workflow; namespace OrderListSolution.OrderItemEventReceiver { /// <summary> /// List Item Events /// </summary> public class OrderItemEventReceiver : SPItemEventReceiver { /// <summary> /// An item is being added. /// </summary> public override void ItemAdding(SPItemEventProperties properties) { SPItemEventDataCollection data = properties.AfterProperties; SPList list = properties.OpenWeb().Lists[properties.ListId]; string fieldName= list.Fields.GetField("订购日").InternalName; var date = DateTime.Parse(data[fieldName].ToString()); if (date > DateTime.Now) { //properties.ErrorMessage = "当前添加的日期不合法"; properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl; properties.RedirectUrl = "/_layouts/OrderListSolution/ErrorPage.aspx"; properties.Cancel = true; } } } }