Scenario:
This is quick snippet to show how to make a entry in Custom List on behalf of the user , even in elevated privileged mode.
Code:
SPContext.Current.Web.AllowUnsafeUpdates = true;Update: My good friend Venkat mentioned that in case of update we should not update 'Author'
SPUser user = SPContext.Current.Web.CurrentUser;
string weburl = SPContext.Current.Web.Url;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(weburl))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["test list"];
SPListItem listItem = list.Items.Add();
listItem["Title"] = string.Format("I am {0}", user.LoginName);
// Modified By
listItem["Editor"] = user;
// Created By
listItem["Author"] = user;
listItem.Update();
}
}
}
);
SPContext.Current.Web.AllowUnsafeUpdates = false;
2 comments:
Good Post.
Thanks!
Thank you!! Was stuck on this one for a while
Post a Comment