Xiaodan Mao
Xiaodan Mao

Reputation: 1706

Pass variable to a javascript function in a c# code

I need to pass a variable to a javascript function,but I got a little trouble. In the .cs file,I write like this:

string id = "someid";
this.Controls.Add(new LiteralControl("<input type=\"button\" onClick=\"myFunction("+id+")\">"));

I need to use the value of this id,but in the console.log(id),it just shows "object",not the "someid",what's the problem?

Upvotes: 0

Views: 316

Answers (4)

kappa
kappa

Reputation: 1569

Use the single quotes around id:

'"+id+"' (notice the single quotes then double quotes)

Upvotes: 2

Travis J
Travis J

Reputation: 82267

The problem is that it is looking for a saved variable on the page named someid, which is why you are getting the object in the console. Pranay Rana has a good solution which is to make sure the string someid is surrounded by single quotes.

Upvotes: 1

Quentin
Quentin

Reputation: 943165

Look at the generated HTML:

<input type="button" onClick="myFunction(someid)">

You are generating a variable name when you want a string literal.

Add some quote marks.


Whenever you have a problem that manifests in the browser: Look at the code the browser is dealing with first. You should always start by determining if the JS you want is not working or if the server side code is not generating the JS you want.

Upvotes: 3

Pranay Rana
Pranay Rana

Reputation: 176896

just add '' around id as i did below will resolve your issue

this.Controls.Add(new LiteralControl("<input type=\"button\" onClick=\"myFunction('"+id+"')\">"));

Upvotes: 2

Related Questions