A nice and easy way to show how you can dynamically create and/or call Javascript from ASP.NET (using C#/Csharp). Of course VB.NET would be very similar I guess!
| item | code |
| 1 | string sJSexe = “<script>alert(‘hello world’);</script>”; |
| 2 | Type t = this.GetType(); |
| 3 | if (!ClientScript.IsClientScriptBlockRegistered(t, “PopupScript”)) { ClientScript.RegisterClientScriptBlock(t, “PopupScript”, sJSexe); } |
So let’s have a quick look at what the code does:
Item 1
Creates the Javascript string with what we want to call.. we could call a function here, or just straight Javascript inline.
Item 2
Get a handle to the host type.. actually you may want to look this up further if you want to know “exactly” what it does!
Item 3
This section actually calls the Javascript. It registers the Javascript once, and obviously the IF check ensures we do not create the function multiple times. The t is the type from Item 2, and PopupScript is essentially the host function we register, and of course the sJSexe variable is the string containing the actual Javascript.
Quite handy, as you can of course intermingle some ASP.NET with the Javascript for example:
string sTestData = Request.Cookies["myCookie"].Value.ToString();
string sJSexe = “<script>alert(‘My Cookie value is: ‘ + sTestData + ‘);</script>”;
Obviously you can access any .NET object/variable etc.. and I have found this very small bit of code extremely useful!! hope it helps you too!
Filed under: Uncategorized

