Saturday, March 24, 2012

Invoke client-script from the server...

I'm trying to be crafty here...I want to inject some client-script into a page, then execute it all without a postback. I thought I could use an update panel and do something like this...

1 <form id="form1" runat="server">
2 <asp:ScriptManager ID="ScriptManager1" runat="server" />
3
4 <script type="text/javascript" language="javascript">
5 document.write(Date());
6 </script>
7
8 <div style="background-color: Brown; border: solid 1px #999;">
9 <asp:Button id="button1" runat="server" onclick="button1_Click" text="clickMe" />
10 </div>
11
12 <asp:UpdatePanel id="updatePanel1" runat="server" updatemode="Conditional" />
13 </form>

CODE BEHIND AS FOLLOW --

1protected void Page_Load(object sender, EventArgs e)2{34}56protected void button1_Click(object sender, EventArgs e)7{8System.Web.UI.HtmlControls.HtmlGenericControl hiddenSpan =new HtmlGenericControl();9hiddenSpan.InnerHtml ="Here is some hidden text that I would like to show without refreshing the page.";10hiddenSpan.ID ="hiddenSpan";11hiddenSpan.Style.Add("display","none");1213updatePanel1.ContentTemplateContainer.Controls.Add(hiddenSpan);1415System.Web.UI.HtmlControls.HtmlGenericControl span =new HtmlGenericControl();16span.InnerHtml ="<script type='text/javascript' language='javascript'>document.getElementById('hiddenSpan').style.display = 'block';</script>";1718updatePanel1.ContentTemplateContainer.Controls.Add(span);1920updatePanel1.Update();21}
Turns out, the entire page refreshes when I attempt this. If I declare the button as a trigger for the update panel then the script won't work at all. Does anyone know how to do something like this? Keep in mind...this isn't my actual project, this is just a small test. My real project wouldn't have the button event...hopefully the update panel refresh and client script would be triggered by a totally different server event.

Add the Button as Trigger. Then Use the ScriptManager.RegisterStartupScript method to inject the js code like the following:

ScriptManager.RegisterStartupScript(this, this.GetType(), "startup", "document.getElementById('hiddenSpan').style.display = 'block';", true);


Bingo! You rock!! I didn't know the scriptmanager had registration events like that!! Thanks.

No comments:

Post a Comment