Call JavaScript via ScriptManager in C#

Executing a block of JavaScript code from C# on the server side in ASP.NET AJAX is relatively easy to do, here in this post I will show how this can be done. The main object that you need to use is the ScriptManager via RegisterClientScriptBlock method; this method let you inject new JavaScript codes into the browser in run-time. That mean you client web browser can order to execute new task by the server ordering it, in this example I will use the DropDownList SelectedIndexChanged event to make event changes.


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call JavaScript via ScriptManager in C#</title>
    <script type="text/javascript">
    function newinput(wording){
        document.getElementById('DivExample').innerHTML = "<p>" + wording + "</p>";
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"  
                    <asp:ListItem Text="item 0"></asp:ListItem>
                    <asp:ListItem Text="item 1"></asp:ListItem>
                    <asp:ListItem Text="item 2"></asp:ListItem>
                <asp:Label ID="RenderLabel" runat="server" Text="Rerender" Visible="false" ></asp:Label>
        <div id="DivExample" style="clear:both;"></div>


using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        ScriptManager scriptManager = ScriptManager.GetCurrent(Page);
            "newinput("You have selected "+ DropDownList1.SelectedValue +"");",

As you can see is that I inject JavaScript code into the RenderLabel which in the UpdatePanel. Therefore you must remember that the control that you want to reference in Async PostBack must be in an UpdatePanel, to be able to work. The control key “runtime” can be anything, example “xyz” I just use “runtime” for easy understanding.

The JavaScript function, you can also inject new functions or call an already rendered function on the client. One example of this usage, is to build an JSON data in the server-side with .NET power and database server, and use a Flash object or Silverlight to render the result in full graphics mode.

I hope you have enjoy this blog, and comment if possible.