Ali_dotNet
Ali_dotNet

Reputation: 3279

sending parameters from ASP.NET to javascript

I want to call a javascript function from my ASP.NET (C#) code, I want to pass a variable (string) with another string like below:

tag_label.Attributes.Add("onmouseover", "tooltip.show('my text'+'"+myString+"'<br/>'another text);");

how should I pass these values? also I want to have new line in my tooltip (<br/>), what should I do? I've tried several ways (using ', + and other methods) to send all these values but I get javascript error, is there any sample? please help me thanks

Upvotes: 0

Views: 632

Answers (4)

rkw
rkw

Reputation: 7297

Two ways:

Method 1 (Jon Martin's way): Have a javascript variable populated by server information

  • Create a javascript variable on the aspx page: var myString = '<%= _mytring %>';
  • Populate _mystring on the code behind: public String _mystring = "your value";

Method 2: Just dump the variable out from the server side

Page.ClientScript.RegisterStartupScript(getType(Page), "var myString = '" + "your value" + "';", true);

Upvotes: 0

Samir Adel
Samir Adel

Reputation: 2499

Try this:

tag_label.Attributes.Add("onmouseover", "tooltip.show('my text','"+myString+"<br/>another text');");

Upvotes: 0

Jason
Jason

Reputation: 15931

You are very close, keep in mind that when controls are generated on the server they are 'unrolled' into HTML on the client -- in other words the '+' sign is unnecessary as the client will only ever see the string (it has no notion of which part of the attribute value was generated in code vs. which part is hard coded on the server).

var toolTip = string.Format("This is text was added on {0}:{1}<br />this text is hard-coded", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()
var attributeValue = string.Format("tooltip.show('{0}')");
tag.Attributes.Add("onmouseover",  attributeValue);

Upvotes: 0

Jon Martin
Jon Martin

Reputation: 3392

In that function, you could use the server side code tag.

var string = "<% = myString%>"

Upvotes: 1

Related Questions