Prev Next |
Most user controls must respond to user interaction. There are several ways to handle user events, such as: using simple asp.net-like postbacks, using the messaging system, and catching events directly in the code-beside class.
Add the following construct to the layout to test each of these forms for handling user events.
<Edit ID="Edit" Width="300" />
</Border>
<Border align="center">
<Button Header="Method" Click="OnMethodButton" />
<Button Header="Message" Click="playground:messagebutton" />
<Button ID="BesideButton" Header="Postback" />
</Border>
The following sections walk through each of the three possible ways of handling the button click event.
5.1. Invoking a Method
Look at the first button:
1. The Header property specifies the text on the button. Note that the Click property is set to “OnMethodButton”.
-
Edit the code-beside class created in this section and add a reference to the Edit control defined above by adding the following field to the class:
protected Sitecore.Web.UI.HtmlControls.Edit Edit;Note: Notice that we’ve used the ID property of the Edit control to reference it. This works in the same way as it does in asp.net.
-
Add the OnMethodButton method:
protected void OnMethodButton()
{
Edit.Value = "OnMethodButton handler";
} - Compile the assembly, make sure that you put it in the /bin folder of your Sitecore installation.
- Refresh the application and click the ‘Method’ button:
5.2. Messaging
Now look at the second button.
Note that the Click property is set to a different value. Add another method to the code-beside class and mark it with HandleMessageAttribute attribute, passing “playground:messagebutton” to its constructor as shown below:
protected void MessageButton(Message message)
{
Edit.Value = "playground:messagebutton handler";
}
Rebuild, refresh, and click the ‘Message’ button to test.
Messaging is a more powerful tool than a simple method invocation. It can be used to communicate with other applications (that is why it is a good practice to prefix your message with a namespace if you intend to use it across applications) and can also have parameters. Explore the Message class to see what it contains.
5.3. Events
You can also use regular .NET events to react to user input. Look at the third button
It doesn’t have a Click property set, so it will simply make a postback when clicked. But the button does have an ID property assigned, which we will use to reference it in code-beside class. We can catch the Clicked event of the button as usual:
// OnLoad method is fired when the form is loading, similar to the asp.net
protected override void OnLoad(EventArgs args)
{
// Subscribe to the event
BesideButton.OnClick += new EventHandler(BesideButton_OnClick);
}
// handle the event
private void BesideButton_OnClick(object sender, EventArgs e)
{
Edit.Value = "BesideButton_OnClick handler";
}
Rebuild, refresh, and click the ‘Postback’ button to test.
Prev Next