Posted By

housecor on 04/08/11


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

danfinrud55


Access server side C# variabes in javascript


 / Published in: JavaScript
 

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

  1. Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "myuniquescriptkey", "<script type=\"text/javascript\" language=\"javascript\">var i = 4;</script>");
  2.  
  3.  
  4. //A more involved example sending down a list of objects in json:
  5. public class Employee
  6. {
  7. public string Name { get; set; }
  8. public string ID { get; set; }
  9. public string Age { get; set; }
  10. }
  11.  
  12. Employee oEmployee1 = new Employee { Name = "Pini", ID = "111", Age = "30" };
  13. Employee oEmployee2 = new Employee { Name = "Yaniv", ID = "Cohen", Age = "31" };
  14. Employee oEmployee3 = new Employee { Name = "Yoni", ID = "Biton", Age = "20" };
  15. List<Employee> oList = new List<Employee>() { oEmployee1, oEmployee2, oEmployee3 };
  16.  
  17. System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
  18. string json = oSerializer.Serialize(oList);
  19.  
  20. Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "myuniquescriptkey", "<script type=\"text/javascript\" language=\"javascript\">var employees = " + json + ";</script>");
  21.  
  22.  
  23. //Then, to parse the list:
  24. jQuery.each(employees, function() {
  25. alert(this.Name);
  26. });

Report this snippet  

You need to login to post a comment.