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

3 Answers 3

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%>;
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

<script type="text/javascript">
  <% string username = Class.PropertName; %>
  var jsUsername = '<%: username %>';
</script>

1 Comment

5 years later and nothing new in your answer. I recommend deleting this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.