简体   繁体   中英

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

在该功能中,您可以使用服务器端代码标签。

var string = "<% = myString%>"

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);

尝试这个:

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM