Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a C# variable to javascript

Tags:

c#

.net

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

like image 356
Seany84 Avatar asked Jan 26 '26 05:01

Seany84


1 Answers

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%>;
like image 145
Rion Williams Avatar answered Jan 28 '26 18:01

Rion Williams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!