Invoke JavaScript from C# code behind [duplicate]

2019-09-05 05:17发布

This question already has an answer here:

I am trying to learn asp.net. Assuming that I have this code:

if (command.ExecuteNonQuery() == 0)
    {
       // JavaScript like alert("true");
    }
    else
    {
        // JavaScript like alert("false");
    }

How to I can invoke JavaScript from C# code behind? How to do that by putting that JavaScript in Scripts directory which is created by default in MS Visual Studio?

enter image description here

4条回答
The star\"
2楼-- · 2019-09-05 05:50

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.

private void LoadClientScriptMessage(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());
 }
查看更多
相关推荐>>
3楼-- · 2019-09-05 05:55

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 example
public static string GetAnalyticsSettingsScript()
{
    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.

private void RegisterAnalyticsSettingsScript()
{
    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. CONFIGURATION
    var 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 OBJECT
    window.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 LOAD
    Project.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.

查看更多
老娘就宠你
4楼-- · 2019-09-05 06:07

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);
查看更多
The star\"
5楼-- · 2019-09-05 06:16

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

public string Name {get; set;} 

JavaScript on Aspx page

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

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

查看更多
登录 后发表回答