Description
Anthem_InvokeControlMethod can be used to invoke methods on user
controls, too.
In this example, we create a user control and add it to the page twice. The user
control calls back to itself using Anthem_InvokeControlMethod.
Example
UserControl
?
UserControl
?
Steps
-
Create a user control (as a .ascx file) and add some HTML to it, a button, and a
span element. The button will trigger a call back to the user control on the
server. The span will have its contents updated so we can see that a change did
occur from clicking the button:
<%@ Control Language="C#" %>
<h3>UserControl</h3>
<button onclick="UpdateUserControl()" type="button">Update</button>
<span id="result"></span>
-
The UpdateUserControl function doesn't exist so we have to inject
into the page hosting the control. We can do that when the user control fires
its Load event. While we're in Page_Load, let's
register the control with Anthem.Manager:
<script runat="server">
void Page_Load()
{
Anthem.Manager.Register(this);
Page.RegisterClientScriptBlock(
GetType().FullName,
@"<script language='javascript' type='text/javascript'>
function UpdateUserControl(userControlID, spanID) {
Anthem_InvokeControlMethod(
userControlID,
'GetNow',
[],
function(result) {
document.getElementById(spanID).innerHTML = result.value;
}
);
}
<" + "/script>"
);
}
</script>
-
Take a closer look at that UpdateUserControl function. It's
requiring two IDs to be passed in as arguments. The first is the ID of the user
control we want to invoke the method on and the second is the ID of the span we
want to update:
function UpdateUserControl(userControlID, spanID) {
Anthem_InvokeControlMethod(
userControlID,
'GetNow',
[],
function(result) {
document.getElementById(spanID).innerHTML = result.value;
}
);
}
-
In order to get those two IDs into the UpdateUserControl function,
we need to modify the button element with the onclick
attribute to pass them in. Getting the user control's ID is easy since we can
use the ClientID property:
<button onclick="UpdateUserControl('<%= ClientID %>')" type="button">Update</button>
-
We want something like ClientID on the span element, too. To get
that, we can make the span element a server-side control:
<span id="result" runat="server"></span>
-
Adding that attribute to the span element gives our user control a
field called result. That field has a ClientID property
which we can access inside the button element's onclick
attribute:
<button onclick="UpdateUserControl('<%= ClientID %>', '<%= result.ClientID %>')" type="button">Update</button>
-
The only thing we're missing is the GetNow method on the user
control:
[Anthem.Method]
public DateTime GetNow()
{
return DateTime.Now;
}
Remarks
Be careful with your quotes! Look closely at the steps that added <%= %>
blocks of code to the UpdateUserControl function call to see
what's quoted and what's being evaluated.