What is the best way to run javascript programmatically when loading an ASP.net page?

In my file global.asaxfor my ASP.net project, I check for specific conditions. When these conditions are met, I want to automatically execute javascript code when the page starts.

This is my code:

if condition Then Response.Write ("<script type =" "text / javascript" ">")
    Response.Write ("// Javascript code to do things")
    Response.Write ("</script>")
End If

While this works to execute Javascript code, I don’t think this is the best practice, because this code will precede the entire HTML page of the loaded page.

What is the best way to programmatically bind to some additional Javascript code that will execute when my page loads?

Refresh Thank you for your reply. Too bad this solution does not work out global.asax. Is it impossible to do this on the site? It seems to global.asaxbe the logical place to put the code that runs with each page ... Response.Writeworks fine in global.asax.

+3
source share
3 answers

To properly control the placement of scripts using controls or server pages, you should use ClientScriptManager.RegisterStartupScript()

You can also use the equivalent method in ScriptManager if you use ajax controls on your site: ScriptManager.RegisterStartupScript

, script , . .

, global.asax, . Global.asax HttpApplication HttpHandler, . , - script .

+7

asp.net ajax 1.0 - Sys.WebForms.PageRequestManager ajax. asp.net 3.5 asp.net ajax, , asp.net ajax javascript , . pageLoaded.

ps: ,

+1

, , .

, , System.Web.UI.Page , javascript.

System.Web.UI.Page

public partial class Orders : MyCode.BasePage
+1

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


All Articles