Friday, April 18, 2008

Permissions error when adding data to a list (programmatically)

MSDN article does not mention this but the code smaple wont work if you copy it directly from the MSDN article. You get an error when you try to add a record in list. Here is the code:
SPSite site = SPContext.Current.Site;
SPWeb localweb = site.OpenWeb();
SPList list = localweb.Lists["User List"];
SPListItem listItem = list.Items.Add();
localweb.AllowUnsafeUpdates = true;
listItem["Title"] = "test";
listItem.Update();
localweb.AllowUnsafeUpdates = false;
This will not work. First thing, you should use elevated privileges to get rid of the permissions exception. Second thing, the SPContext should be used outside the elevated privilges code. Here is how to do it correctly:

SPWeb webroot = null;
try
{
webroot = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(webroot.Site.ID))
{
using (SPWeb localweb = site.OpenWeb(webroot.ID))
{
SPList list = localweb.Lists["User List"];
SPListItem listItem = list.Items.Add();
localweb.AllowUnsafeUpdates = true;
listItem["Title"] = fname.Value.ToString();
listItem.Update();
localweb.AllowUnsafeUpdates = false;
}
}
});
Instantiate the SPWeb object to null. Assign SPContext outside elevated privileges. Set AllowUnsafeUpdates to true before updating the item.

No comments:

Post a Comment