Reputation: 5596
I have the following block of code in my header:
<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..";
}
However, I am getting an error message:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Does anyone know how I can pass a C# variable from my code behind into this jQuery function without getting that error?
Thanks in advance
Upvotes: 2
Views: 5605
Reputation: 1410
Accessing a server-side c# variable/property within an .aspx page.
<script type="text/javascript">
<% string username = Class.PropertName; %>
var jsUsername = '<%: username %>';
</script>
Upvotes: 0
Reputation: 76547
For a dynamic string:
That seems like it would work, try wrapping the code blocks with quotes, as such:
'<%= GetUserName() %>'
also you may have to use a this
statement to access that method:
'<%= this.GetUserName() %>'
For a static string:
Declare your string as a public string in your aspx page:
public string UserName = "somestring..";
and access it via:
var userName = <%=this.UserName%>;
Upvotes: 6
Reputation: 172220
This is a well-known problem when trying to add controls to a page that contains code blocks.
A simple workaround is to use data binding expressions instead, i.e., to use <%# ... %>
instead of <%= ... %>
. Note that you will have to call this.DataBind();
in your Page_Load event
for this to work.
(BTW, remember that the code you insert in JavaScript will need to be properly quoted.)
Upvotes: 3