Skip to content Skip to sidebar Skip to footer

Invoke Javascript From C# Code Behind

I am trying to learn asp.net. Assuming that I have this code: if (command.ExecuteNonQuery() == 0) { // JavaScript like alert('true'); } else { // Jav

Solution 1:

Here is method I will use from time to time to send a pop message from the code behind. I try to avoid having to do this - but sometimes I need to.

privatevoidLoadClientScriptMessage(string message)
{
    StringBuilder script = new StringBuilder();

    script.Append(@"<script language='javascript'>");
    script.Append(@"alert('" + message + "');");
    script.Append(@"</script>");

    Page.ClientScript.RegisterStartupScript(this.GetType(), "messageScript",    script.ToString());
 }

Solution 2:

You can use RegisterStartupScript to load a javascript function from CodeBehind.

Please note that javascript will only run at client side when the page is render at client's browser.

Regular Page

Page.ClientScript.RegisterStartupScript(this.GetType(), "myfunc" + UniqueID, 
     "myJavascriptFunction();", true);

Ajax Page

You need to use ScriptManager if you use ajax.

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myfunc" + UniqueID, 
      "myJavascriptFunction();", true);

Solution 3:

Usually these "startupscripts" are handy for translations or passing settings to javascript. Although the solution Mike provided is correct on the .Net side I doubt in a clean (read: no spaghetti code) production environment this is a good practice. It would be better to add .Net variables to a javascript object like so:

// GA examplepublicstaticstringGetAnalyticsSettingsScript()
{
    var settings = new StringBuilder();
    var logged = ProjectContext.CurrentUser != null ? "Logged" : "Not Logged";
    var account = Configuration.Configuration.GoogleAnalyticsAccount;

    // check the required objects since it might not yet exist
    settings.AppendLine("Project = window.Project || {};");
    settings.AppendLine("Project.analytics = Project.analytics || {};");
    settings.AppendLine("Project.analytics.settings = Project.analytics.settings || {};");
    settings.AppendFormat("Project.analytics.settings.account = '{0}';", account);
    settings.AppendLine();
    settings.AppendFormat("Project.analytics.settings.logged = '{0}';", logged);
    settings.AppendLine();

    return settings.ToString();
}

And then use the common Page.ClientScript.RegisterStartupScript to add it to the HTML.

privatevoidRegisterAnalyticsSettingsScript()
{
    string script = GoogleAnalyticsConfiguration.GetAnalyticsSettingsScript();
    if (!string.IsNullOrEmpty(script))
    {
        Page.ClientScript.RegisterStartupScript(GetType(), "AnalyticsSettings", script, true);
    }
}

On the JavaScript side it might look like this:

// IIFE
(function($){
    // 1. CONFIGURATIONvar cfg = {
        trackingSetup: {
            account: "UA-xxx-1",
            allowLinker: true,
            domainName: "auto",
            siteSpeedSampleRate: 100,
            pluginUrl: "//www.google-analytics.com/plugins/ga/inpage_linkid.js"
        },
        customVariablesSetup: {
            usertype: {
                slot: 1,
                property: "User_type",
                value: "Not Logged",
                scope: 1
            }
        }
    };

    // 2. DOM PROJECT OBJECTwindow.Project = window.Project || {};
    window.Project.analytics = {
        init: function(){
            // loading ga.js here with ajax
        },
        activate: function(){
            var proj = this,
                account = proj.settings.account || cfg.trackingSetup.account,
                logged = proj.settings.logged || cfg.customVariablesSetup.usertype.value;

            // override the cfg with settings from .net
            cfg.trackingSetup.account = account;
            cfg.customVariablesSetup.usertype.value = logged;

            // binding events, and more ...
        }
    };

    // 3. INITIALIZE ON LOADProject.analytics.init();

    // 4. ACTIVATE ONCE THE DOM IS READY
    $(function () {
        Project.analytics.activate();
    });
}(jQuery));

The advantage with this setup is you can load an asynchronous object and override the settings of this object by .Net. Using a configuration object you directly inject javascript into the object and override it when found.

This approach allows me to easily get translation strings, settings, and so on ... It requires a little bit knowledge of both.

Please note the real power of tis approach lies in the "direct initialization" and "delayed activation". This is necessary as you might not know when (during loading of the page) these object are live. The delay helps overriding the proper objects.

Solution 4:

This might be a long shot, but sometimes I need a c# property/value from the server side displaying or manipulated on the client side.

c# code behind page

publicstring Name {get; set;} 

JavaScript on Aspx page

var name = '<%=Name%>';

Populating to client side is generally easier, depending on your issue. Just a thought!

Post a Comment for "Invoke Javascript From C# Code Behind"