简体   繁体   中英

Create a Sharepoint Blog comment in code

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.

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;

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

}});

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?

好的,Posttitle是一个SPLookupField,必须由以下内容填充:“ {ID}#; {Title}”

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM