Use a C# const in javascript

I’ve got some purposely misnamed objects (SQL Server Reporting Services reports in this case) in a project and I want to refer to them, both server-side and client-side, from the same place so that when I get ready to change the names of the objects to their real/final names I’ll only have to change them in one place…

In a public static class, set the names of the reports/objects to a const like so…

public static class MyStaticClass
{
    public const string FoobarReportName = "foobar";
}

In an aspx page, in the case of this particular ASP.Net MVC project I used the Site.Master page, enter a script tag with a javascript global declaration like so…

        <script type="text/javascript">
            var foobarReportName = '<%= MyStaticClass.FoobarReportName %>';
        </script>

Now you can use foobarReportName in your javascript like so…

function SubmitThisForm(reportName) {
    if (foobarReportName == reportName) {
        alert('foobarReportName is ' + foobarReportName);
    }
}

Advertisements

About w4ik

software engineer...in the trenches
This entry was posted in ASP.Net, mvc. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s