rainhamtown
rainhamtown

Reputation: 171

Sending objects to a Javascript function in C#

There are many ways to achieve this i know, but what is the preffered method when sending data from C# to a javascript function? Here is a simple working example of a JSON object in C# being passed to a JS function on the client side using attributes.add(). Is there a different way of achieving this?

c# code:

    public string BuildJSONText()
    {
        List<City> cities = new List<City>();
        cities.Add(new City("London", "Britain", "Europe"));
        cities.Add(new City("Tokyo", "Japan", "Asia"));
        cities.Add(new City("New York", "USA", "North America"));

        return (new JavaScriptSerializer()).Serialize(cities);
    }

    protected void getJSON(object sender, EventArgs e)
    {
        string test = BuildJSONText();
        getJsonBtn.Attributes.Add("onclick", "getJSON(" + BuildJSONText() + ")");
    }

Javascript:

   function getJSON(obj){

        alert(obj[0].Name);            
  ;}

Thanks for your help

Upvotes: 5

Views: 218

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Using a JSON serializer (as you do) is IMHO the best and most secure way of sending entire object graphs from the server to a client side method. It will take care of properly encoding all dangerous characters that might be contained and thus ensuring that the client side won't break, it protects from XSS and it also preserves arrays.

Upvotes: 3

Related Questions