我的标题中有以下代码块:
<script type="text/javascript">
$(document).ready(function () {
$('#target').readmytweet({
'color': 'black',
'search': 'from:' + <%= GetUserName() %>,
'user': <%= GetUserName() %>,
'width': 600,
'tweets': 10,
'speed': 25
});
})
</script>
protected string GetUsername()
{
return "somestring..";
}
但是,我收到一条错误消息:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
有谁知道如何将我的代码中的 C# 变量传递到此 jQuery 函数中而不会出现该错误?
提前致谢
最佳答案
对于动态字符串:
这似乎行得通,尝试用引号将代码块括起来,如下所示:
'<%= GetUserName() %>'
您可能还必须使用 this
语句来访问该方法:
'<%= this.GetUserName() %>'
对于静态字符串:
在您的 aspx 页面中将您的字符串声明为公共(public)字符串:
public string UserName = "somestring..";
并通过以下方式访问它:
var userName = <%=this.UserName%>;
关于c# - 将 C# 变量添加到 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6997856/