It took me quite a while to figure out what happened with my code of emitting javascript.
I need to show or hide a textbox based on the selected item from a dropdownlist control.
First I prepared a client static js code:
function showHideAmountToBox(ddlAmtRelId, txtAmtToId)
{
if(document.all[ddlAmtRelId].selectedIndex == 5){
Hide_Show(txtAmtToId, 'show');
}
else{
clear(txtAmtToId);
Hide_Show(txtAmtToId, 'hide');
}
}
Because of a control's id is dynamically rendered by ASP.Net(it is really rigid because we can not use javascript to control DOM easily other than dynamically emit javascript from ASP.Net codebebind.)
Then, I emit the following code to hook the showing/hiding logic to dropdownlist control:
this.ddlAmtCmp.Attributes.Add("OnChange", "showHideAmountToBox('" + ddlAmtCmp.ClientID + "','" + this.txtAmountTo.ClientID + "')");
It works when the page is firstly requested, but after, the control is always hidden as by default. The reason is that a callback doesn't bring the show/hide status along, but rather, the initial (default) status stored in the Viewstate goes along.
To keep the control's client status, I emit the following javascript to call the showHideAmountToBox so as to recover the status by rerun the logic.
Client.RegisterStartupScript(typeof(Page), "AmountSync", "showHideAmountToBox('" + ddlAmtCmp.ClientID + "','" + this.txtAmountTo.ClientID + "')", true);
This is the normal way ASP.Net emits javascript. But the function not get called. Why? The first time requesting the page, it get called, why not the later times? The difference is that the first time is a normal request, the later times are Anthem callbacks. With Anthem callbacks, the response gives to Anthem, not immediately rendered by browser, and Anthem won't execute the script except using it's own way.
Realized this, I changed the way of emitting javascript with the following
string js = "showHideAmountToBox('" + ddlAmtCmp.ClientID + "','" + this.txtAmountTo.ClientID + "');";
Anthem.Manager.Register(this);
Anthem.Manager.AddScriptForClientSideEval(js);
The I got through.
No comments:
Post a Comment