Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject Javascript from asp.net code behind files

Tags:

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.

like image 570
cdub Avatar asked Aug 12 '11 21:08

cdub


People also ask

How Register JavaScript code behind in C#?

Solution 2Both RegisterClientScript and RegisterStartupScript use to add javascript code in web form between <form runat="server"> tag and </form> tag. RegisterClientScript adds javascript code just after <form runat="server"> tag while RegisterStartupScript adds javascript code just before </form> tag.

How can I access JavaScript variable from code behind in C#?

To get JavaScript values in the code-behind, we need Hidden Input Control, whose runat attribute we will set to runat="Server" so that it can be accessible in code-behind. It will work as an intermediately to pass the value from client-side to server-side.


1 Answers

You can use registerstartupscript instead of registerclientscriptblock!

RegisterStartupScript When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM

RegisterClientScriptBlock When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error

Difference between registerstartupscript and registerclientscriptblock

protected void Page_Load(object sender, System.EventArgs e)
 {
      string myScript = "\n<script type=\"text/javascript\" language=\"Javascript\" id=\"EventScriptBlock\">\n";
        myScript += "alert('hi');";
        myScript += "\n\n </script>";
     Page.ClientScript.RegisterStartupScript(this.GetType(), "myKey", myScript, false);
 }
like image 60
Pir Abdul Avatar answered Nov 02 '22 12:11

Pir Abdul