Quantcast
Channel: SharePoint 2013 - Development and Programming forum
Viewing all articles
Browse latest Browse all 7589

Programmatically add webpart to page in sharepoint 2013.

$
0
0

I am trying to add webpart using following code:

public void AddTaskListsWebPart()
        {
            SPLimitedWebPartManager manager = null;
            SPFile file = null;

            try
            {
                //SPSecurity.RunWithElevatedPrivileges(delegate()
                //{
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                        {
                            web.AllowUnsafeUpdates = true;

                            file = web.GetFile(SPContext.Current.Site.Url.ToString() + "/Pages/" + Utility.PageName.Tasks.ToString()+ ".aspx");
                            if (file != null && file.CheckOutStatus  == SPFile.SPCheckOutStatus.None)
                            {
                                file.CheckOut();
                                
                                manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
                                TaskLists objTaskLists = new TaskLists();
                                manager.AddWebPart(objTaskLists, "zone1", 0);
                                manager.SaveChanges(objTaskLists);

                                file.Update();
                                web.Update();
                            }

                            web.AllowUnsafeUpdates = false;
                        }
                    }
                //});
            }
            catch (Exception ex)
            {
                Utility.SPTraceLogError(ex);
            }
            finally
            {
                if (manager != null)
                    manager.Dispose();

                if (file != null)
                {
                    file.CheckIn("added web parts");
                    file.Publish("added web parts");
                }
            }
        }

But unfortunately getting following error from step file.checkin step:

"Updates are currently disallowed on GET requests.  To allow updates on a GET, set the 'AllowUnsafeUpdates' property on SPWeb."

Thanks in advance.


Viewing all articles
Browse latest Browse all 7589

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>