Search code examples
c#dotnetnukedotnetnuke-module

How to add a module on my page in DNN programatically


So far, I have tried below code to add a module through code on my page in DNN.

 protected void Page_Load(object sender, EventArgs e)
{
       ModuleController MC = new ModuleController();
       ModuleInfo MInfo = new ModuleInfo();
       MInfo = MC.GetModule(507, 116,false);//Just Hard coded for testing 
       MInfo.TabID = PortalSettings.ActiveTab.TabID;
       MInfo.PaneName = "ContentPane";
       MInfo.Alignment = "left";
       MC.AddModule(MInfo);//Line throwing error :-

}

I am trying to add a module which is present on tabid=116 and having moduleId=507 on my current tab or page in pageLoad Event.But the last line throwing a error saying

"Violation of UNIQUE KEY constraint 'IX_TabModules_UniqueId'. Cannot insert duplicate key in object 'dbo.TabModules'. The duplicate key value is (555ba77a-be19-40a0-bb72-559672230345)."

Please tell me where i am doing wrong ? and is this the correct way to add a module ?


Solution

  • The first thing that I notice is that you're effectively trying to add the same instance of the module to the database. You've changed the TabID, but otherwise all of the other IDs within the ModuleInfo instance are still there.

    Looking at how DNN adds an existing module (look in the DoAddExistingModule method), they start by calling Clone() on the ModuleInfo instance, and then reset the UniqueId (which is the constraint you're hitting):

    newModule.UniqueId = Guid.NewGuid();