Add an MVC Widget To a Page Programmatically - Front- & Back-End Development - Front- & Back-End Development - Progress Community
 Front- & Back-End Development

Add an MVC Widget To a Page Programmatically

  • Add an MVC Widget To a Page Programmatically
  • Question is pretty straightforward: how do you add mvc widgets to pages programmatically? Something like this: Add control to a page
  • var pageNode = manager.GetPageNode(pageId);
    var template = manager.GetTemplates().Single(x => x.Name == "TicketOmaha.home");
    AddPageTemplate(manager, pageNode, template);
    AddContentBlockWidgetToPage(manager, pageNode, "Content");
    private static void AddContentBlockWidgetToPage(PageManager pageManager, PageNode pageNode, string placeholder)
        //pageManager.Provider.SuppressSecurityChecks = true;
        using (var mvcWidget = new Telerik.Sitefinity.Mvc.Proxy.MvcControllerProxy())
        
            mvcWidget.ControllerName = typeof(ContentBlockController).FullName;
     
            mvcWidget.Settings = new Telerik.Sitefinity.Mvc.Proxy.ControllerSettings(new ContentBlockController()
            
                Content = "[Placeholder Example For Control Associated With This Production]"
            );
     
            CreateControl(pageManager, pageNode, mvcWidget, "ContentBlock", placeholder);
        
     
    private static void AddPageTemplate(PageManager manager, PageNode pageNode, PageTemplate template)
        var pageData = pageNode.GetPageData();
        var temp = manager.EditPage(pageData.Id);
        temp.TemplateId = template.Id;
        manager.PagesLifecycle.CheckIn(temp);
        manager.SaveChanges();   
     
    private static void CreateControl(PageManager pageManager, PageNode pageNode, Telerik.Sitefinity.Mvc.Proxy.MvcControllerProxy mvcWidget, string widgetCaption, string placeHolder)
        var page = pageManager.EditPage(pageNode.GetPageData().Id, CultureInfo.CurrentUICulture);
        var draftControlDefault = pageManager.CreateControl<PageDraftControl>(mvcWidget, placeHolder);
        draftControlDefault.Caption = widgetCaption;
        pageManager.SetControlDefaultPermissions(draftControlDefault);
        draftControlDefault.SiblingId = GetLastControlInPlaceHolderInPageId(page, placeHolder);
        page.Controls.Add(draftControlDefault);
        pageManager.PagesLifecycle.CheckIn(page);
        pageManager.SaveChanges();
     
    private static Guid GetLastControlInPlaceHolderInPageId(PageDraft page, string placeHolder)
        var id = Guid.Empty;
        var controls = new List<PageDraftControl>(page.Controls.Where(c => c.PlaceHolder == placeHolder));
        while (controls.Count > 0)
        
            var control = controls.SingleOrDefault(c => c.SiblingId == id);
            id = control.Id;
     
            controls.Remove(control);
        
        return id;