Reputation: 315
I have the need to create Sharepoint blog comments by code:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
sw.AllowUnsafeUpdates = true;
SPList spList = SPContext.Current.Web.Lists["Kommentare"];
SPListItem listItem = spList.Items.Add();
listItem[listItem.Fields["Titel des Beitrags"].InternalName] = SPContext.Current.Item["Title"];
listItem[listItem.Fields["Titel"].InternalName] = titlearea.Value;
listItem[listItem.Fields["Textkörper"].InternalName] = CommentArea.Value;
listItem[SPBuiltInFieldId.Author] = curUser;
//listItem[SPBuiltInFieldId.Modified] = curUser;
listItem.Update();
//spList.Update();
sw.AllowUnsafeUpdates = false;
});
but I always get a "Invalid data has been used to update the list item. The field you are trying to update may be read only"
I tried Systemupdate and the values seem to be valid.
Upvotes: 1
Views: 2409
Reputation: 5830
This works, verified
public static void AddComment(string url)
{
using (SPSite site = new SPSite(url))
{
site.AllowUnsafeUpdates = true;
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList commentList = web.Lists["Comments"];
SPListItem newItem = commentList.AddItem();
newItem["Body"] = "body";
newItem["Title"] = "title";
newItem["PostTitle"] = "2;#post1";
newItem.Update();
}
}
}
You may be writing a read-only field, like Author.
Upvotes: 0
Reputation: 315
Ok, the Posttitle is a SPLookupField, and has to be filled by: "{ID}#;{Title}"
Upvotes: 0
Reputation: 1615
listItem[listItem.Fields["Titel des Beitrags"].InternalName] = SPContext.Current.Item["Title"];
Does SPContext.Current.Item point to a refence to the blog post you are adding the comment to?
By this I mean is your code running in a custom web part that replaces the standard "Add comments" web part on a blog post?
Upvotes: 0
Reputation: 9127
Maybe this is unrelated to your problem but you are creating the SPWeb object (or using the context) outside the delegate, if a user without proper privileges runs the code, it will not elevate properly. Do something like this:
SPSecurity.RunWithElevatedPrivileges(delegate {
using (SPSite elevatedSite = new SPSite(SPContext.Current.Site.ID))
using (SPWeb elevatedSite = elevatedSite.RootWeb)
{
//impl
}});
Upvotes: 0
Reputation: 935
I think the Author field is readonly and sharepoint automattically asign the loggined user name there.
So could you try it after commenting the line listItem[SPBuiltInFieldId.Author] = curUser;
Upvotes: 1