The easiest way to insert custom code into a portal engine-based website is using standard ASCX user controls. This chapter will show you how to do this. If you're not familiar with Visual Studio development, you can skip this chapter.
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 in the Solution Explorer window and click New Folder. Name the folder the same as the code name of your site, e.g. CorporateSite - this folder will be exported with your project when you decide to export the site and import it on a live server.
Right-click the new folder 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.
Click Add. Switch to the Design tab and drag and drop the following controls and set their properties:
|•||Text: Show current time|
|•||Text: <clear the value>|
Double-click the Show current time button and enter the following code into the Button1_Click method:
Label1.Text = DateTime.Now.ToString();
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 - the user controls are compiled at run time.
Save all changes.
Adding the user control on the page
Sign in to Kentico CMS Desk, click the Home page and click Design. Remove the web part in the zoneCenter zone and click the Add web part () button in this zone. Choose the General/User control web part. Enter the following value in the User control virtual path property:
(the folder name must reflect the folder that you previously created)
The ~ character represents the root of your web application. Click OK. Click the Live site mode and now you can see the user control in the page. When you click the Show current time button now, the current date and time is displayed next to the button:
In this short example, you have seen that you can easily add any custom code developed as an ASCX user control in Visual Studio. This user control can contain any .NET controls, third-party controls or ADO.NET code that will retrieve data from an external database.
User controls versus web parts
Another option how to insert custom code into the page is creating your own web part. A web part is basically an ASCX user control, but it inherits some standardized properties and methods from the CMSAbstractWebPart class. You will usually build web parts in case you need to create re-usable, parameterized user controls. Web part development is described in the Development -> Web parts -> Developing web parts topic.