Seany84 Seany84 - 1 year ago 85
C# Question

Adding a C# variable to javascript

I have the following block of code in my header:

<script type="text/javascript">
$(document).ready(function () {
'color': 'black',
'search': 'from:' + <%= GetUserName() %>,
'user': <%= GetUserName() %>,
'width': 600,
'tweets': 10,
'speed': 25

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

Answer Source

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%>;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download