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.

Default.aspx

<%@ 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>";
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
                    onselectedindexchanged="DropDownList1_SelectedIndexChanged">
                    <asp:ListItem Text="item 0"></asp:ListItem>
                    <asp:ListItem Text="item 1"></asp:ListItem>
                    <asp:ListItem Text="item 2"></asp:ListItem>
                </asp:DropDownList>
                <asp:Label ID="RenderLabel" runat="server" Text="Rerender" Visible="false" ></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>
        <div id="DivExample" style="clear:both;"></div>
    </div>
    </form>
</body>
</html>

Default.aspx.cs

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);
        ScriptManager.RegisterClientScriptBlock(
            RenderLabel,
            RenderLabel.GetType(),
            "runtime",
            "newinput("You have selected "+ DropDownList1.SelectedValue +"");",
            true);
    }
}

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.


Kick It on DotNetKicks.com

  • Dusan

    Hi,

    just wondering if you’ll have an idea why (after implementing simmilar code) I get some kind of a Page reload with not all the code reloaded… The case can be seen here:

    http://svetijuraj.windows-1.domovanje.com/potapljanje-ob-hrvaski-obali.aspx

    Try the “Gallery button” on the right. It will show you photos gallery. Then click “Galerija naslednja stran” and it will show you new photos. The photos are loaded from this ascx:

    <asp:NextPreviousPagerField PreviousPageText=”
    NextPageText=” ButtonCssClass=”PagerButton” />

    <a id=”FullPhoto” runat=”server” href=”
    class=”highslide” onclick=”return hs.expand(this)”>

    <asp:Label ID=”Label1″ runat=”server” Text=”>

    <a href=”#” id=”linkprevious” runat=”server” class=”previous” onclick=”return hs.previous(this)”
    title=”><a href=”#” id=”linknext”
    runat=”server” class=”next” onclick=”return hs.next(this)” title=”>
    <a href=”#” id=”linkmove” runat=”server” class=”highslide-move” onclick=”return false”
    title=”><a href=”#” id=”linkclose” runat=”server”
    class=”close” onclick=”return hs.close(this)” title=”>

    and the code behind returns this javascript:

    protected void ResizePhotos(object sender, EventArgs e)
    {
    ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), “PartResize”, “PartialResize();”, true);
    }

    The script itself posts ok and does it’s job (animating the photos one by one). But there are 2 problems I’ve noticed:

    1. The metadata of the page changes (you’ll see the switch to “title” which is not written anywhere in the code)
    2. Other javascript that is implemented on the photos (something to do with administration of them if you’re logged in) is also missing.

    Any idea?

  • http://www.sarin.mobi Sarin Na Wangkanai

    I think it because you are using the typeof(Page), in cause the effect.

    or it because you have;

    <a href=”#” id=”linkmove” runat=”server” class=”highslide-move” onclick=”return false” title=” rel=”nofollow” >

    with the tittle without a closing comma ” to it. you just leave if open?

    Hope that helps

  • Dusan

    Nope, had typeof set to Datapager (that actually trigers postback) and Listview before and the effect was the same. Actually changed it because of that.

    As for the quotes (“), they’re not open => it just seems that when I pasted the code to this commentbox, it deleted the server code. The title comes from Resources.language file, so in the code there’s actually:

    In the site-code produced you’ll notice there’s text enclosed by quotes.

  • http://www.sarin.mobi Sarin Na Wangkanai

    if i where you, i check out the resources.language procedure, is it reading the Key or the Value?

  • Dusan

    It is reading the value. Is it possible to read the key? Haven’t seen that yet…

  • http://www.sarin.mobi Sarin Na Wangkanai

    it should read the value, if you are reading the key it would like get the “title”.

    key: title
    english value: “this is my language title
    thai value: “นี้คือหัวเรื่องของฉัน”

  • http://mikeknowles.com Mike Knowles

    Thanks for this tip especially the explanation about using a control within an UpdatePanel. I googled many pages and this was the only one to explicitly point that out, which was exactly what I needed to know. I had been sending the user control reference my code was in and nothing was happening. I added a Literal to the ASCX called JavaScriptLiteral and then used that and it worked great. Here’s a little utility method if anyone wants it:

    private void RegisterStartupScript(string script)
    {
    System.Web.UI.ScriptManager.RegisterStartupScript(this.JavaScriptLiteral,
    this.JavaScriptLiteral.GetType(), this.JavaScriptLiteral.ClientID, script, true);
    }

    for this to work you need a control in UpdatePanel ContentTemplate defined as:

    Thanks,
    Mike Knowles
    mikeknowles.com

  • http://www.sarin.mobi Sarin Na Wangkanai

    Your welcome, happy to be at help. :)

  • http://profiles.google.com/vapcguy Thomas Jackson

    What if you have a “The property or indexer ‘System.Web.UI.ScriptManager’ cannot be used in this context because the get accessor is inaccessible” error when you try to type in ScriptManager scriptManager = ScriptManager.GetCurrent(Page); in the Page_Load section?  How do you “expose” the ScriptManager so you don’t get this error?  Also have an error that says the ScriptManager is a property but is being used as a type.

  • TamilNadu

    Thanks a lot. It works perfectly

  • Satish Hirpara

    gud 1

  • Rabha Shoaib

    how can i generate polygon by using this scenarion? plz help me in this regards

  • http://www.facebook.com/sarath.pavithran.58 Sarath Pavithran

    can i use this with dynamically loading user control into a place holder ……please help me