Where to register RegisterClientScriptBlock in ASP.NET?

Where is the best part of the asp.net page or code for registration RegisterClientScriptBlock.

+3
source share
2 answers

You have a set of options.

The registration script includes in your section <head>or inline tags <script>. I prefer my scripts to be at the bottom of the page.

You can also register it at the level Pagein Page_Load(or any other event) by calling ClientScript.RegisterClientScriptBlockand passing it the script you want. Remember that if you go with RegisterClientScriptBlock, you will need to make sure that you register the code every time the page loads, so I would recommend an event Page_Loadif you want to use this method.

For instance:

protected void Page_Load(object sender, EventArgs e)
{
    AddClientSideJavascript();
    // Do other stuff
}


private void AddClientSideJavascript()
{
    // Register some client script code
    Type someType = this.GetType();
    if (!ClientScript.IsClientScriptBlockRegistered(someType, "TESTSCRIPT"))
    {
        string script = "function ShowAlert() { alert('Test'); }";
        ClientScript.RegisterClientScriptBlock(someType, "TESTSCRIPT", script, true);
    }

    // Register more here... etc...
}

Just make sure that you don’t include the part of yours Page_Loadthat was wrapped in the tag if (!IsPostBack), otherwise your scripts will not be registered after any postbacks.

+3
source

The correct answer is at any time in page_load.

0
source

Source: https://habr.com/ru/post/1745016/


All Articles