2012-05-15 51 views
2

我是Sharepoint的新手。 我有一個EventReceiver掛鉤到ItemUpdated事件,我想寫一個字段中的文本。 當我上傳一個文件的事件觸發好的時候,它通過調試代碼,似乎更新,但我的財產並沒有收到它應該的文本。但是,當我點擊頁面刷新後,我可以看到更新的值。ListItem值在ItemUpdated上沒有更新,僅在點擊刷新後

這裏是我的代碼

public override void ItemUpdated(SPItemEventProperties properties) 
    { 
     base.ItemUpdated(properties); 

     string folderPath = string.Empty; 
     SPListItem item = properties.ListItem; 
     if (item.File.ParentFolder != null) 
     { 
      folderPath = item.File.ParentFolder.ServerRelativeUrl; 
     } 

     AssignPropertyToField("Folder Name", item, folderPath); 
    }   

    private void AssignPropertyToField(string fieldName, SPListItem item, string folderPath) 
    { 
     item[fieldName] = folderPath; 

     this.EventFiringEnabled = false; 
     item.SystemUpdate(); 
     this.EventFiringEnabled = true; 
    } 

預先感謝您的建議,

問候,

回答

3

如果可能,請嘗試ItemUpdating而不是ItemUpdated

由於ItemUpdated是異步的,您不應該指望在頁面刷新之前調用它。通過ItemUpdating,請注意列表項目尚未保存,因此您無需致電SystemUpdate

public override void ItemUpdating(SPItemEventProperties properties) 
{ 
    string folderPath = string.Empty; 
    SPListItem item = properties.ListItem; 
    if (item.File.ParentFolder != null) 
    { 
     folderPath = item.File.ParentFolder.ServerRelativeUrl; 
    } 
    properties.AfterProperties["FolderNameInternalName"] = folderPath; 
}   

在你的情況,這個問題將是你是否能夠檢索ItemUpdating事件中更新的父文件夾的信息。我上面的示例代碼將採用先前存在的文件夾信息。如果該文件被移動到不同的文件夾,此代碼會給你錯誤的URL。

+0

謝謝,你在說什麼是有道理的。但我有兩個問題。 1)我現在不在工作,所以我無法測試,但我已嘗試ItemUpdating並收到代碼爲0x81020015的異常。可能是因爲在那個事件中,properties.ListItem對象是空的? 2)你提到我根本不需要調用SystemUpdate(),我是否也應該避免調用Update()?謝謝, –

+1

對於#1,我不確定是什麼導致了錯誤,但是properties.ListItem不應該爲null。對於ItemAdding而言,它將爲空,但對於ItemUpdating則不會。對於#2,這是正確的。您無需致電更新,因爲列表項目已在更新。 ItemUpdating事件允許您在更新實際保存之前進行最後一分鐘的更改(或完全取消更改)。 –

+0

但是,我正在嘗試應用您的解決方案:在事件ItemUpdating中,properties.AferProperties集合的計數爲0.是否有任何具體原因,我是否做錯了什麼? –

1

你可以叫item.Update()而不是item.SystemUpdate()

請注意,通過這種方式,ItemUpdated事件處理程序將被調用兩次,因此,如果item [fieldName]與AssignPropertyT中的folderPath不同,則需要確保僅執行更新oField,避免無限循環。

+0

謝謝你是有用的信息,但仍然不回答我的問題。儘管如此,謝謝你。我嘗試使用Update而不是UpdateSystem,但沒有任何改變。字段保持空白,並且只在頁面刷新後更新 –