开发者

Sending objects to a Javascript function in C#

开发者 https://www.devze.com 2023-03-22 00:47 出处:网络
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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号