How do I pass data from c# to jquery/javascript?

后端 未结 5 652
情书的邮戳
情书的邮戳 2021-01-27 18:42

I have a function that I\'d like to run when the page loads, so either in document.ready or pageLoad.

Using jquery, I\'ll trigger the function using its class name

5条回答
  •  無奈伤痛
    2021-01-27 19:17

    What you can do is, use JQuery Ajax call to retrieve server side data.

    But that would require you to set up service that would be exposed. You could do it in a shortcut way with out setting up the service.

    But that would require messy logic.(its a short cut :))

    You could create a property in your page which exposes the JSON Data as string. You could read the JSON data in your javascript by following

    var data =<% GetData() %>
    

    You can define a ToJson on object to convert the object in to JSON String

        public static string ToJSON(this object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer(new SimpleTypeResolver());
            return serializer.Serialize(obj);
        }
    
    public string GetData()
    {
        return (new {SomeData}).ToJson();
    }
    

    Note SomeData is a class containing your data(i.e array of urls) or what ever representation you choose.

    Then loop over data to build the dynamic html

提交回复
热议问题