2

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

Seany84
  • 5,526
  • 5
  • 42
  • 67

3 Answers3

6

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%>;
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
3

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

Community
  • 1
  • 1
Heinzi
  • 167,459
  • 57
  • 363
  • 519
0

Accessing a server-side c# variable/property within an .aspx page.

<script type="text/javascript">
  <% string username = Class.PropertName; %>
  var jsUsername = '<%: username %>';
</script>
chri3g91
  • 1,196
  • 14
  • 16