c# - 将 C# 变量添加到 javascript

标签 c# .net

我的标题中有以下代码块:

 <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/

相关文章:

c# - 将嵌套的 json 字符串解析为字符串列表

c# - 多线程中 SaveOrUpdate 上的 NHibernate TransientObjectException

c# - source.StartWith(x).Replay(1) 和 source.Publish(x) 有什么区别

c# - 无法找到属性 [rollingStyle] 在 [log4net.Appender.FileAppender] 上设置对象

c# - 无法在单元测试中加载文件或程序集“System.Web.Mvc”

c# - 如何通过相同的函数对我的代码进行多线程处理以同时处理多个文件?

c# - C#代码中的美元符号是什么意思?

c# - gridview 根据值更改文本颜色

c# - Winforms 中的所有者表单

c# - FtpWeb请求 : The remote server returned an error: (530) Not logged in