Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

Asp.Net

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

Javascript

<script type="text/javascript">

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

    initObject.backg.product_line = JavascriptBlah;

</script>

Adding this to the page

 public string blah { get; set; }


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

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

like image 703
Nick LaMarca Avatar asked Jun 13 '12 18:06

Nick LaMarca


3 Answers

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";
        //....
like image 191
Nick Rolando Avatar answered Sep 21 '22 22:09

Nick Rolando


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.

like image 38
mlorbetske Avatar answered Sep 21 '22 22:09

mlorbetske


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:

document.getElementById("param1").value
like image 20
Dante Avatar answered Sep 24 '22 22:09

Dante