我想在字符串中添加变量。
这是我的代码
btnAddHelp.Attributes.Add(" onclick","返回确认('您确定要将__ 变量 __导航到其他页面吗?&#39 );&#34);
我的问题是撇号
答案 0 :(得分:2)
简单连接。不确定是什么问题?
btnAddHelp.Attributes.Add("onclick", "return confirm('Are you sure to navigate " + __variable__ + " to other page?');");
或者您可以使用String.Format
String myString = String.Format("return confirm('Are you sure to navigate {0} to other page?');",__variable__);
btnAddHelp.Attributes.Add(myString);
答案 1 :(得分:1)
使用字符串格式化和javascript转义的另一种解决方案:
btnAddHelp.Attributes.Add("onclick", string.Format("return confirm('Are you sure to navigate{0} to other page?');", HttpUtility.JavaScriptStringEncode(your_variable_here)));
答案 2 :(得分:1)
这里有一些方法,所有方法都是不同形式的字符串连接。
连接运算符+
最基本的方法是简单地打破你的初始字符串并添加你的变量。
var script = "return confirm('Are you sure to navigate " + __variable__ + " to other page?');";
btnAddHelp.Attributes.Add("onclick", script);
String.Format()
方法可以帮助您将变量作为参数传递给字符串(它将根据传入的参数的索引替换占位符元素{0}
)。如果您在同一个字符串中重用变量,这将非常有用。
var script = String.Format("return confirm('Are you sure to navigate {0} to other page?');",__variable__);
btnAddHelp.Attributes.Add("onclick", script);
String Interpolation(可在C#6 +中使用)
C#6引入了一个更优雅的String.Format()
方法替代方法,允许您使用{}
括号将要直接使用的变量注入字符串中的特定位置。
var script = $"return confirm('Are you sure to navigate {__variable__} to other page?');"
btnAddHelp.Attributes.Add("onclick", script);
关于您的变量
您提到您遇到有关引号的问题。这些通常可以在任何上述建议中处理,但是如果引号存在于您的变量中,那么您可能需要详细说明它(即它是字符串吗?它看起来像什么?等)