Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass variables from c# to javascript?

Looking to pass variables from c# to javascript to use some jquery code. Passing doubles, ints, strings, arrays. Does anyone know how to do this?

for example if I have this code snip in c#:

string blah = "this is a blah string";

I would like to pass this into javascript so that I could use a mouseover event in jquery:

$('#myDiv').mouseover(function(){ //do something with my 'blah' string });
like image 485
locoboy Avatar asked Aug 24 '10 04:08

locoboy


People also ask

Can you pass variables by reference in C?

To pass a value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to, by their arguments.

How do you pass variables?

In order to pass a value using call by reference, the address of the arguments are passed onto the formal parameters. It is then accepted inside the function body inside the parameter list using special variables called pointers.

What is parameter passing in C?

Parameter passing involves passing input parameters into a module (a function in C and a function and procedure in Pascal) and receiving output parameters back from the module. For example a quadratic equation module requires three parameters to be passed to it, these would be a, b and c.

Can you pass functions in C?

Till now, we have seen that in C programming, we can pass the variables as an argument to a function. We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.


2 Answers

Nevermind I think I figured it out. Assuming the code above, you can write in javascript:

<script type="text/javascript"> var JavascriptBlah = '<%=blah%>'</script>

This will pass the blah in c# to the JavascriptBlah on the client side. Then you can manipulate on client side.

like image 69
locoboy Avatar answered Sep 23 '22 22:09

locoboy


You can use public properties on the code behind as well as the session. Here is a sample using public properties that can be read from a Javascript function.

Front End:

function IsAgentInProgram()
{
    var optStatus = "<%=AgentOptInStatus%>";

    if (optStatus == "True")
        alert("You are opted in!");
    else
        alert ("You are opted OUT");
}

Code Behind:

public bool AgentOptInStatus;

private void Page_Load(object sender, System.EventArgs e)
{
    this.AgentOptInStatus = true;

}
like image 32
Flea Avatar answered Sep 23 '22 22:09

Flea