Wednesday, June 24, 2009

Calling javascript from code behind

Previously, we know how to easily call server side method from javascript. The opposite is also simple enough.

Just use the RegisterClientScriptBlock method of ClientScriptManager (in case of full postback) or ScirptManager (in case of patial postback). Following is an example:

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "confirmInPageNav", "<script>confirmInPageNav()</script>", false);



confirmInPageNav can be any javascript function

Tuesday, June 16, 2009

Calling server side method from client (using javascript)

I didn't know how easy to achieve this until I read the post in this link:
http://disturbedbuddha.wordpress.com/2008/01/08/executing-server-side-code-from-javascript/

The essence is to put the server side logic in a button's OnClick event handler; then use the HTML DOM click() method to raise the OnClick event.

<script type="text/javascript">

function myClientButton_onclick() {

document.getElementById('btn1').click();

}

script>

<asp:Button ID="btn1" runat="server" Text="Original" OnClientClick="alert('abc')" onclick="btn1_Click" />

<input id="myClientButton" type="button" value="Press Me" onclick="return myClientButton_onclick()" />

Note that the HTML DOM click() method also raises btn1's OnClientClick event.

Wednesday, June 10, 2009

FindControlByID

When we want to find a control by its ID, chances are it is usually nested in many levels. In this scenario, we need more powerful method than the .NET framework provided Control.FindControl.

Writing such a method actually is straightforward enough:

private static Control FindControlByID(Control root, string id)
{
if (id == string.Empty)
return null;

if (root.ID == id)
return root;

foreach (Control c in root.Controls)
{
Control t = FindControlByID(c, id);
if (t != null)
{
return t;
}
}
return null;
}

It works great no matter there is master page involved or not; no matter how many levels the control hierarchy has.

Tuesday, June 2, 2009

Using Validator as a Label

Occasionally, we have several validation logic and for some of them we use the validators ASP.NET provides and for some of them we may want to write our own code and have a label displaying the error message. As we know, a validator control has a label to display its error message. By using the validator's label, we can save a label control and more importantly, it may be easier for the layout. (This may not be a good practice since we are letting the validator doing some work it is not supposed to do. I want to log it anyway since sometimes this can be handy)

In our own logic, if we want to use the RequireFieldsValidator's (rfvVersion) build-in label to display our custom error message, we can write:

rfvVersion.IsValid = false;
rfvVersion.Text = "Incorrect Format";
rfvVersion.Enabled = true;