Alex Rivera | Logout

Inject Javascript from asp.net code behind files

Asked 2011-08-12T21:35:25.997
22

Am I injecting this correctly?

string myScriptName = "EventScriptBlock";
string myScript = string.Empty;

//Verify script isn't already registered
if (!ClientScript.IsClientScriptBlockRegistered(myScriptName))
{
    Response.Write('b');
    myScript = "\n<script type=\"text/javascript\" language=\"Javascript\" id=\"EventScriptBlock\">\n";
    myScript += "alert('hi');";
    myScript += "\n\n </script>";

    ClientScript.RegisterClientScriptBlock(this.GetType(), myScriptName, myScript);
}

This is in my Page_Load, but I never see an alert and I have no JavaScript errors either.

Edit
Report

2 Answers

6

Both RegisterStartupScript and RegisterClientScriptBlock will work.

Problem lies in myScript (string variable).In myScript variable you need to use alert variable only, as whenever you use this, script tag will be added automatically to your page's HTML at runtime. To check this right on your page and see the source of the page.

protected void Page_Load(object sender, EventArgs e)
{
        string myScript = string.Empty;

        //myScript = "\n<script type=\"text/javascript\" language=\"Javascript\" id=\"EventScriptBlock\">\n";
        string registerKey = "alert('RegisterClientScriptBlock');";
        myScript = "alert('RegisterStartupScript');";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "RegisterStartupScript", myScript, true);
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "RegisterClientScriptBlock", registerKey, true);
    }

Note: I have executed RegisterStartupScript first and than RegisterClientScriptBlock.But RegisterStartupScript alert will be executed at last, as it will be added at the end of the page. RegisterClientScriptBlock will always be added at the starting of the page.

answered 2013-06-24T09:58:47.860
3

You should use RegisterStartupScript.

answered 2011-08-12T21:39:47.263

Your Answer