Pass C# Values To Javascript

On loading the page I want to pass a value to my javascript function from a server side variable.

I cannot seem to get it to work this is what I have:


protected void Page_Load(object sender, EventArgs e)
    string blah="ER432";

<script type="text/javascript">

    var JavascriptBlah = '<%=blah%>';

    initObject.backg.product_line = JavascriptBlah;


Adding this to the page
 public string blah { get; set; }

        protected void Page_Load(object sender, EventArgs e)

I still am getting an error:
CS0103: The name ‘blah’ does not exist in the current context

Also I would like to try and accomplish this without using hdden fields


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I believe your C# variable must be a class member in order to this. Try declaring it at the class level instead of a local variable of Page_Load(). It obviously loses scope once page_load is finished.

public partial class Example : System.Web.UI.Page
    protected string blah;

    protected void Page_Load(object sender, EventArgs e)
        blah = "ER432";

Method 2

In this particular case, blah is local to Page_Load you’ll have to make it a class level member (probably make it a property) for it to be exposed like that.

Method 3

You can put a hidden input in your html page:

<input  type="hidden" runat='server' id="param1" value="" />

Then in your code behind set it to what you want to pass to your .js function:
param1.value = "myparamvalue"

Finally your javascript function can access as below:

Method 4

What I’ve done in the past is what webforms does as it’s functionality–creating a hidden field to store values needed by the client. If you’re using 4.0, you can set the hidden field client id mode to static to help keep things cleaner as well. Basically, add you value to the hidden field and then from javascript you can get the value or modify it too(in case you want to pass it back) since it’s just a dom element.

If you really want to use code–like a variable, it needs to be accessible at the class scope.

Method 5

Your string blah needs to be a public property of your Page class, not a local variable within Page_Load. You need to learn about scoping.

public class MyPage
    public string blah { get; set; }

    protected void Page_Load(object sender, EventArgs e)
        blah = "ER432";

Method 6

You should declare blah at class level.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x