5

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Is it still passed to the javascript function in the same way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.