Thursday, July 03, 2008

Accessing the Properties of a Web User Control from JavaScript

I ran into this situation where I have a web user control (*.ascx file), in this control I defined some properties that will control the appearance and the logic of the user control

public partial class WebUserControl : System.Web.UI.UserControl
{

protected void Page_Load(object sender, EventArgs e)
{
}
public string Address
{ get; set; }
}


I wanted to be able access this property from JavaScript from the web page that hosts the user control like this

document.getElementById('<%=WebUserControl1.ClientID %>').Address

My idea is as follows:

- Add a hidden input control to the user control

- Override the ClientID property of the user control to return the ClientID of the hidden input, so when you write the following JavaScript in the page hosting the user control

document.getElementById('<%=WebUserControl1.ClientID %>').Address

what will happen is that you will set the value of an attribute on the hidden input

this will allow us to access the user controls properties from the JavaScript, but there will be a problem : these attributes that are set on the client side will not be posted back to the server

we need to take these values from the attributes and put them in the "value" field of this hidden input control because we can read the "value" field at the server. so i added the following JavaScript function that reads the attributes values of the hidden input and puts these values in the "value" field of the hidden input


function ReadAttributedProperties(objID)
{
if (document.getElementById(objID)==null)
return;
var atts=document.getElementById(objID).attributes;
var value='';
for(var j=0;j<atts.length;j++)
{
if (atts[j].specified)
{
if (atts[j].nodeName!='id' && atts[j].nodeName!='name'
&& atts[j].nodeName!='type' && atts[j].nodeName!='value' )
{
value+= atts[j].nodeName+ ':' + atts[j].nodeValue;
if (j!= (atts.length-1))value += ',';
}
}
}
document.getElementById(objID).value=value;
}

To make things simpler i created a class that inherits UserControl and do all of this for you, all you have to do is to create a user control that inherits this class and define your properties as follows


public partial class WebUserControl : ScriptedUserControl.ScriptedServerControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string Address
{
get
{
return GetPropertyValue("Address");
}
set
{
SetPropertyValue("Address", value);
}
}
}

You can download the source code and a sample web site from here

1 comment:

Anonymous said...

Hello,

I would like to access the property in the same usercontrol... How to do that?