Access server side C# variabes in javascript


/ Published in: JavaScript
Save to your folder(s)

Options:
1. Write the desired values into a hidden field that contains json. Reference the hidden field by ID and parse the json to get the desired vars.
2. Call a webmethod that returns the values in json format
3. Write js via the code-behind that writes the variables to the page in a separate script tag. The js is placed inline in the page. Call: Page.ClientScript.RegisterClientScriptBlock. See example below.


So why is putting the entire javasscript in a string within the code-behind a lousy idea?
1. No code coloring
2. No syntax checking
3. Have to escape quotes which makes it hard to read and adds work
4. JS isn't cached since it's a string sitting within the html, unlike an attached .js file.
5. No separation of concerns. Client script should ideally be in a .js file to keep server side business logic from being intermingled with other concerns.
6. Inability to reuse. A useful .js file can be called from multiple pages. js stored in a string of a code-behind is page specific.
7. No IDE assistance for formatting or intellisense support

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.