Kentico CMS 6.0 Tutorial  

Adding custom code to your website

Adding custom code to your website

Previous topic Next topic Mail us feedback on this topic!  

Adding custom code to your website

Previous topic Next topic JavaScript is required for the print function Mail us feedback on this topic!  

The easiest way how to insert custom code into a portal engine-based website is using standard ASCX user controls. This topic will show you how to do this. If you are not familiar with Visual Studio development, you can skip this topic.

 

Current time example

 

In this example, we will create a simple user control (ASCX) using Visual Studio and integrate it into our home page.

 

Open the website project using the WebProject.sln file that is placed in the folder where you deployed the website. Right-click the web project root in the Solution Explorer window and click the Add new item... option. Choose to create a new Web User Control and set its name to GetTime.ascx. You can set the programming language option to either Visual C# or Visual Basic.

 

tutorial_clip0065

 

Click Add. Switch to the Design tab, drag and drop the following controls and set their properties:

 

Button control:

 

ID: Button1

Text: Get time

 

Label control:

 

ID: Label1

Text: <clear the value>

 

tutorial_clip0066

 

Double-click the Get time button and add the following code to the Button1_Click method:

 

[C#]

 

Label1.Text = DateTime.Now.ToString();

 

[VB.NET]

 

Label1.Text = DateTime.Now.ToString()

 

This code ensures that the label displays the current date and time when the button is clicked. It's not necessary to compile the project — user controls are compiled at run time.

 

Save both the ASCX and ASCX.CS files.

 

Adding the user control on the page

 

Sign in to Kentico CMS Desk, select the Home page and click Design. Add (AddWebPart) a web part of type General -> User control to the zoneCenter web part zone. Enter the following value into the User control virtual path property: ~/GetTime.ascx

 

The ~ character represents the root of your web application. Click OK. Click the Live site mode and now you can see the user control inserted onto the page. When you click the Get time button now, the current date and time is displayed next to the button:

 

tutorial_clip0067

 

User controls versus web parts

 

Another option how to insert custom code onto a page is to create your own web part. A web part is basically also an ASCX user control, but it inherits some standardized properties and methods from the CMSAbstractWebPart class. You should build web parts in case you need to create re-usable, parameterized user controls. The development of web parts is described in the next chapter.