DotNetNuke 5 module development tutorial - part 5: The edit control

17. February 2010 22:24

To Visual Basic version

This time we are going to create ourselves an edit control. We start with the markup, so open EditProducts.ascx. Make it look like this:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="EditProducts.ascx.cs" Inherits="SipidCode.Modules.Products.EditProducts" %>
<%@ Register TagPrefix="dnn" TagName="TextEditor" Src="~/controls/TextEditor.ascx"%>
<table width="650" border="0" summary="Edit Product Item">
 <tr>
  <td width="75">Name</td>
  <td><asp:TextBox ID="Name" runat="server"></asp:TextBox></td>
 </tr>
 <tr>
  <td>Description</td>
  <td><dnn:TextEditor ID="Description" runat="server" height="200" width="510" /></td>
 </tr>
</table>
<p>
    <asp:linkbutton cssclass="CommandButton" id="cmdUpdate" resourcekey="cmdUpdate" runat="server" borderstyle="none" text="Update" OnClick="cmdUpdate_Click"></asp:linkbutton>&nbsp;
    <asp:linkbutton cssclass="CommandButton" id="cmdCancel" resourcekey="cmdCancel" runat="server" borderstyle="none" text="Cancel" causesvalidation="False" OnClick="cmdCancel_Click"></asp:linkbutton>&nbsp;
    <asp:linkbutton cssclass="CommandButton" id="cmdDelete" resourcekey="cmdDelete" runat="server" borderstyle="none" text="Delete" causesvalidation="False" OnClick="cmdDelete_Click"></asp:linkbutton>&nbsp;
</p>

Open EditProducts.ascx.cs. In the region “Private Members” the class variable ItemId is declared. This is where we store the ID of the product item to edit.
Insert the following code into the empty Page_Load method (we deleted the method body in the previous part, remember?):

if ((Request.QueryString["ItemId"] != null))
{
 ItemId = Int32.Parse(Request.QueryString["ItemId"]);
}

Now we have the product item ID in the ItemId variable, if supplied. If there was no ItemId parameter in the query string this means that we should create a new item instead of editing an existing one.

Add the following code:

if (!IsPostBack)
{
 if (!Null.IsNull(ItemId))
 {
  cmdDelete.Attributes.Add("onClick", "javascript:return confirm('" + Localization.GetString("DeleteItem") + "');");
  ProductsController dc = new ProductsController();
  ProductsInfo itm = dc.GetProduct(ModuleId, ItemId);
  if (itm != null)
  {
   Name.Text = itm.Name;
   Description.Text = itm.Description;
  }
  else
  {
   Response.Redirect(Globals.NavigateURL(), true);
  }
 }
 else
 {
  cmdDelete.Visible = false;
 }
}

This only has to be done the first time the page is loaded so we wrap it in a check for IsPostBack. In the case when an ItemId is supplied we add some client script to get a confirmation when deleting an item. Then we fetch the product item with the current module ID and item ID as keys and populate the controls. If there is no matching item, something must be wrong. In that case we redirect the heck out of there, back to the view page.
When an ItemId is not supplied, this means we should create a new item. Just hide the Delete button.

Error handling is always a good thing, so wrap everything in Page_Load in a try-catch. The Page_Load method should now look something like this:

protected void Page_Load(object sender, System.EventArgs e)
{
 try
 {
  if ((Request.QueryString["ItemId"] != null))
  {
   ItemId = Int32.Parse(Request.QueryString["ItemId"]);
  }
  if (!IsPostBack)
  {
   if (!Null.IsNull(ItemId))
   {
    cmdDelete.Attributes.Add("onClick", "javascript:return confirm('" + Localization.GetString("DeleteItem") + "');");
    ProductsController dc = new ProductsController();
    ProductsInfo itm = dc.GetProduct(ModuleId, ItemId);
    if (itm != null)
    {
     Name.Text = itm.Name;
     Description.Text = itm.Description;
    }
    else
    {
     Response.Redirect(Globals.NavigateURL(), true);
    }
   }
   else
   {
    cmdDelete.Visible = false;
   }
  }
 }
 catch (Exception ex)
 {
  Exceptions.ProcessModuleLoadException(this, ex);
 }
}

The error handling code displays an error message to the user, which is enough for us right now.

Insert the following as method body for cmdCancel_Click:

Response.Redirect(Globals.NavigateURL(), true);

Next in line is the implementation of cmdUpdate_Click. Basically we check if we got an ItemId or not and thereby decide if we should update an existing item or create a new one.
cmdUpdate_Click should look like this:

protected void cmdUpdate_Click(object sender, EventArgs e)
{
 try
 {
  ProductsController controller = new ProductsController();
  ProductsInfo productItem = new ProductsInfo()
  {
   ModuleId = ModuleId,
   ItemId = ItemId,
   Name = Name.Text,
   Description = Description.RichText.Text
  };
  if (Null.IsNull(ItemId))
  {
   controller.AddProduct(productItem);
  }
  else
  {
   controller.UpdateProduct(productItem);
  }
  Response.Redirect(Globals.NavigateURL(), true);
 }
 catch (Exception exc)
 {
  Exceptions.ProcessModuleLoadException(this, exc);
 }
}

One thing to note about the code above is how we pull the content from the Description TextEditor control. If you use Description.Text you will get the HTML encoded content (“<” is converted to “&lt;” and so on) which is not what you want in this case. Use Description.RichText.Text and you will get the raw markup.

The last event handler is cmdDelete_Click. If we have an ItemId then we delete the corresponding product item from the database. Simple as that. cmdDelete_Click should look like this:

protected void cmdDelete_Click(object sender, EventArgs e)
{
 try
 {
  if (!Null.IsNull(ItemId))
  {
   ProductsController controller = new ProductsController();
   controller.DeleteProduct(ModuleId, ItemId);
  }
  Response.Redirect(Globals.NavigateURL(), true);
 }
 catch (Exception exc)
 {
  Exceptions.ProcessModuleLoadException(this, exc);
 }
}

 With that done, compile the project to make sure everything is ok. Then log in as host in your DotNetNuke website. Now we’re going to add our brand new edit control to the Products module. Go to Host > Module Definitions. Locate the Products row in the list and click the edit icon.

Products module definition row

Scroll down to the section Module Controls and click Add Module Control.

Product module controls

Make the following settings and click Update:

Edit control definition

Now we can at last create product items and edit them. Great! Try it out!
Go to the page where you added the Products module. Make sure you are in edit mode. Now click the Add Content link. This time it actually happens something interesting. You should now see the edit control with a text field for product name and a text editor for description. Enter some text in them and click Update. The product you just added should now appear in the product list.
Now click the edit (pencil) icon next to the product name. This will take you to the edit screen and let you edit the product item.
Play around with your nice new controls until next time, when we look at the settings control.

Tags: , ,

DotNetNuke | Modules | Tutorials

Comments

4/13/2010 10:42:38 PM #

emilio

when i try the tutorial i can´t see the edit page i see a blank page again.
i managed to view the edit page by putting "Edit" as key field value instead of "EditItem". i´m using DotNetNuke Version:5.2.3

thanks for the tutorial (so good for me)

Cuando  probe el tutorial no pude ver la pagina de edicion yo veia una pagina en blanco otra vez. consegui ver la pagina de edición poniendo "Edit" como valor del campo Key en lugar de "EditItem". estoy usando la verison DotNetNuke Version:5.2.3

gracias por el tutorial (para mi ha servido de mucho)

emilio Spain |

9/12/2010 10:48:54 AM #

AnhDuc.bkhn

thanks your comments, i put "Edit" as ky field value instead of "EditItem".

Its working.

AnhDuc.bkhn Vietnam |

10/13/2010 7:16:03 PM #

fred

I think I discovered how to discover the proper module key to fix the blank edit/update screen. When you click on "Add Content", and the screen renders blank (header, but no module), look at the URL. Right after the "ctl" node you'll find the proper key. I'm playing around with two different modules and the urls are:

http://localhost/dnnsandbox/Sandbox/tabid/63/ctl/EditItem/mid/386/Default.aspx
http://localhost/dnnsandbox/Employees/Request/tabid/62/ctl/Edit/mid/384/Default.aspx

In the first case, the key needed to be "EditItem". For the second module, the key needed to be "Edit".

I'm not sure where the key gets set in DNN or VS, but using the URL to match what the key should be seems to work.

fred United States |

4/13/2010 11:43:35 PM #

Eunice Pisha

Ok thanks

Eunice Pisha United States |

4/17/2010 5:38:59 AM #

suntan

I was very pleased to find this site.I wanted to thank you for this wonderful read!! I definitely enjoyed every little bit of it and I have you bookmarked to check out new stuff you post.

suntan United States |

4/29/2010 3:28:08 PM #

Asperto

Hi
Great tutorial.
I have got as far as Tut 5 (The Edit Module.)
It all compiles, but clicking "Add Content" brings up a new page with a blank module in it.  No errors.
The only thing I notice is a problem recognising "~/controls/textedit.ascx".
I get a warning:-
Warning  76  File '~/controls/TextEditor.ascx' was not found.  
I followed the instructions on using the local iis and overriding the root url.
The designer did show an error control, but now doesn't show a texteditor.
(Using DNN 5.2.2 Community and VS2008 set up for .NET Framework 3.5)
I'm learning a lot though.
Thanks

Asperto United Kingdom |

4/30/2010 1:24:24 PM #

Asperto

Tutorial is vague as to the role of the main DNN solution in VS2008.
It doesn't explain whether this is
1)an app run as a sub-project of the DNN app, or
2)a completely separate, but linked Solution in a separate instance of VS2008.
I've tried both, neither one gets EditProducts.ascx working for me.  Both compile and ViewProducts.ascx shows up for both methods.
Debugging can't be done from the module project if separated.(setup 2).
I think the module should be a Web App in its own instance of VS2008, but I had to work this out after reading a completely separate tutorial.
I set up the vanilla template as a web app, and it installed and ran with full edit.

Asperto United Kingdom |

7/21/2010 6:27:59 AM #

Anhduc.bkhn

thanks thanks

Anhduc.bkhn Vietnam |

10/13/2010 7:24:36 PM #

fred

I think I discovered how to discover the proper module key to fix the blank edit/update screen. When you click on "Add Content", and the screen renders blank (header, but no module), look at the URL. Right after the "ctl" node you'll find the proper key. I'm playing around with two different modules and the urls are:

http://localhost/dnnsandbox/Sandbox/tabid/63/ctl/EditItem/mid/386/Default.aspx
http://localhost/dnnsandbox/Employees/Request/tabid/62/ctl/Edit/mid/384/Default.aspx

In the first case, the key needed to be "EditItem". For the second module, the key needed to be "Edit".

I'm not sure where the key gets set in DNN or VS, but using the URL to match what the key should be seems to work.

fred |

8/17/2011 10:24:05 PM #

Ryan

It gets the information from the EditUrl() call. You can find it in the Optional Interfaces Region in the ViewProducts.ascx.cs file.

Ryan Canada |

8/17/2011 10:42:23 PM #

Ryan

as well as EditUrl() in ProductsList_ItemDataBound() in the ViewProducts.ascx.cs

Ryan Canada |

1/13/2011 1:13:01 AM #

Selva Sabaratnam Selvarajah

Brilliant work!!  I am a DNN newbie.  Thanks to this series of tutorials I am now able to create my own Modules. Just tested the package too under a different DNN install and my module works beautifully.  Time to get back to building more serious modules. Thanks a lot for sharing !!  I have had trouble building modules using the steps outline in a book on the same subject and thank god I came across your tutorials. Please keep up the good work.  What a wonderful world this is!!!

Selva Sabaratnam Selvarajah United States |

1/13/2011 8:47:22 AM #

Johan

Thank you for the feedback and for brightening my day!
Happy coding!

Johan Sweden |

2/26/2011 1:19:11 PM #

Edit screen not showing controls

I added edit html tags in EditProducts.ascx, after following all the procedures the code is working fine and the module is working file. but when am try to add new item it not showing me controls in the edit mode

Any suggestions

Edit screen not showing controls India |

3/10/2011 11:59:37 AM #

Johan

Hm. No, don't have any suggestions there, sorry.

Johan Sweden |

3/11/2011 12:35:59 PM #

Lyndon Bredenkamp

Great tutorial, thank you!

Lyndon Bredenkamp United Kingdom |

4/11/2011 11:56:20 PM #

Amir Alami

Great tutorial

Amir Alami Iran |

4/25/2011 10:20:34 PM #

Jeremy Cummings


I also have an issue with the following include not working. the TextEditor dnn control is not found. This also seems to cause the EditProducts.cs page not to compile. I have included your code exactly as you have provided. I get the following messages:

Error  29  'System.Web.UI.UserControl' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'System.Web.UI.UserControl' could be found (are you missing a using directive or an assembly reference?)  C:\Users\jeremy\Documents\My Web Sites\dotnetnuke1\DesktopModules\Products\EditProducts.ascx.cs  81  41  Products


Error  36  'System.Web.UI.UserControl' does not contain a definition for 'RichText' and no extension method 'RichText' accepting a first argument of type 'System.Web.UI.UserControl' could be found (are you missing a using directive or an assembly reference?)  C:\Users\jeremy\Documents\My Web Sites\dotnetnuke1\DesktopModules\Products\EditProducts.ascx.cs  140  47  Products


Any help much appreciated.

Jeremy Cummings Canada |

4/26/2011 6:19:27 PM #

Johan

This usually happens when VS is unable to find the DNN DLLs. Just to check: have you followed the steps in part 2 really, really (yes, I mean really) carefully?
When you are sure that is in order, force VS to recreate the designer file. I usually try to provoke VS into doing that by viewing the user control in design mode, adding some control to it (a Label or whatever), saving and closing the file, reopen it and remove the control I just added.
You can also edit the designer file manually and specify the correct control type. Or declare the control variable in your code behind file instead. VS will then remove its own control variable from the designer file.

Johan Sweden |

8/10/2011 1:23:40 AM #

Rag

Excellent tutorial, It helped me to better understand the DNN Module development, but it would be nice if you also explain how to consume webServices as the source of the data when working with distributed applications. Thanks.

Rag Mexico |

1/19/2012 7:59:07 AM #

Hosting Services

A very nice article is written in this blog and all the thought are expressing through this article. In this article the way of expressing thoughts are very nice and it is short and sweet which i like the most here.

Hosting Services United States |

1/27/2012 5:36:49 PM #

Ahmad Ahmadi

Thanks For This Great Tutorial !!

Ahmad Ahmadi Iran |

4/10/2012 8:11:53 AM #

sudhakar


How can i include javascripts(.js files) in dotnetnuke edit.ascx file?
$(document).ready(function ()
$('pnlCrop#imgCrop').imageCrop({ overlayOpacity: 0.25 }); //ascx script

Here its calling .imagecrop which is Scripts/jquery.Jcrop.js file , which i registered as follows in ascx.cs file as follows .

Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "Jcrop", (this.TemplateSourceDirectory + "/Scripts/jquery.Jcrop.js"));
Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "jquery.Jcrop.min", (this.TemplateSourceDirectory + "/Scripts/jquery.Jcrop.min.js"));
I need jcrop.min.js file to be executed for croping of images. When i register jcrop.min.js file, the main scritp which is in ascx page is not working. How can i make it work? I want the crop images which I have selected.

sudhakar India |

5/11/2012 5:02:27 AM #

pingback

Pingback from duyanhpham.wordpress.com

HÆ°á»›ng dẫn viết module DNN 5 – DotNetNuke 5 module development tutorial  « Phạm Duy Anh

duyanhpham.wordpress.com |

6/21/2012 8:27:21 AM #

Eduard

I had same errors as Jeremy:
Error  29  'System.Web.UI.UserControl' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'System.Web.UI.UserControl' could be found (are you missing a using directive or an assembly reference?)  C:\Users\jeremy\Documents\My Web Sites\dotnetnuke1\DesktopModules\Products\EditProducts.ascx.cs  81  41  Products


Error  36  'System.Web.UI.UserControl' does not contain a definition for 'RichText' and no extension method 'RichText' accepting a first argument of type 'System.Web.UI.UserControl' could be found (are you missing a using directive or an assembly reference?)  C:\Users\jeremy\Documents\My Web Sites\dotnetnuke1\DesktopModules\Products\EditProducts.ascx.cs  140  47  Products


My solution was:
1. Change EditProducts.ascx file as:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="EditProducts.ascx.cs" Inherits="PMP.Modules.Products.EditProducts" %>
<%@ Reference Control="~/controls/TextEditor.ascx" %>
<table width="650" border="0" summary="Edit Product Item">
<tr>
  <td width="75">Name</td>
  <td><asp:TextBox ID="Name" runat="server"></asp:TextBox></td>
</tr>
<tr>
  <td>Description</td>
  <td><aspTonglaceHolder runat="server" ID="PlaceHolder1" /></td>
</tr>
</table>
<p>
    <asp:linkbutton cssclass="CommandButton" id="cmdUpdate" resourcekey="cmdUpdate" runat="server" borderstyle="none" text="Update" OnClick="cmdUpdate_Click"></asp:linkbutton>&nbsp;
    <asp:linkbutton cssclass="CommandButton" id="cmdCancel" resourcekey="cmdCancel" runat="server" borderstyle="none" text="Cancel" causesvalidation="False" OnClick="cmdCancel_Click"></asp:linkbutton>&nbsp;
    <asp:linkbutton cssclass="CommandButton" id="cmdDelete" resourcekey="cmdDelete" runat="server" borderstyle="none" text="Delete" causesvalidation="False" OnClick="cmdDelete_Click"></asp:linkbutton>&nbsp;
</p>

2. Changed EditProducts.aspx.cs file as:
Added: private DotNetNuke.UI.UserControls.TextEditor Description;
after private int ItemId = Null.NullInteger;

and the added programatically the Control:
        protected void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                Description = (DotNetNuke.UI.UserControls.TextEditor)LoadControl("~/controls/TextEditor.ascx");
                Description.Height = 200;
                Description.Width = 510;
                PlaceHolder1.Controls.Add(Description);

Eduard Australia |

12/8/2014 2:18:03 AM #

pingback

Pingback from akshayanswers.org

Debugging DotNetNuke Modules | Yocom Answers

akshayanswers.org |

Comments are closed

About the addict

Johan Seppäläinen lives in Uppsala, Sweden. He spends most of his days working as a systems architect/developer, specialized in solutions built on Microsoft platforms.
Occasionally there is time for some recreational coding, when he pursues optimal solutions and code zen, mainly in C#. When he is not writing in this blog, that is.