problem with RegisterClientScriptBlock

494 Views Asked by At

i have to run following javascript through one of my method. But its not running Whats wrong with the code.

private void fillGrid1()
{
        GridView1.DataSource = myDocCenter.GetDsWaitingForMe(Session["UserID"].ToString());
        HiddenField1.Value = { myDocCenter.GetDsWaitingForMe(Session["UserID"].ToString()).Tables[0].Rows.Count).ToString();
        GridView1.DataBind();

        String csname1 = "PopupScript1";
        String csname2 = "ButtonClickScript1";
        Type cstype = this.GetType();

        // Get a ClientScriptManager reference from the Page class.
        ClientScriptManager cs = Page.ClientScript;


        // Check to see if the client script is already registered.
        if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
        {
            StringBuilder cstext2 = new StringBuilder();
            cstext2.Append("<script type=\"text/javascript\"> ");

            // You can  add JavaScript by using "cstext2.Append()".

            cstext2.Append("var count = document.getElementById('ctl00_ContentPlaceHolder1_HiddenField2');");
            cstext2.Append("var count = '100';");
            cstext2.Append("document.getElementById('sp2').innerHTML = count;");
            cstext2.Append("script>");

            cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
        }
}
4

There are 4 best solutions below

1
rahul On

Your script tag is not properly closed.

Change

cstext2.Append("script>");

to

cstext2.Append("</script>");
0
Paul On

On top of what adamantium said, your JS looks a bit strange. You seem to declare and set the count variable twice - did you mean to do this.

Following that, best thing to do, render the page then view source. is your JS getting rendered to the page? try and stick an alert in there... is it firing?

0
ram On
>   cstext2.Append("var count =
> document.getElementById('ctl00_ContentPlaceHolder1_HiddenField2');");

I would use the ClientID property here. HiddenField2.ClientID

0
Jakub Linhart On

RegisterClientScriptBlock emits the script just after the <form> tag openning. Browser executes this script just after the tag openning as well but referenced elements are not processed yet at this time - browser cannot find them.

RegisterStartupScript method emits the script just before the <form> tag ending. Nearly all page elements are processed by the browser at this place and getElementById could find something.

See http://jakub-linhart.blogspot.com/2012/03/script-registration-labyrinth-in-aspnet.html for more details.