Search code examples
c#javascriptweb-servicesasmxwebmethod

How do you get the value of a static variable of a class from a list with Javascript


I have a javascript application which get's the data from a C#-WebMethod. The WebMethod returns a List of objects. The class of the obect has a static attribute and I will read this attibute in javascript. The code explains the problem probably better:

The Class:

public class DayEntryBT{
     public static string date { get; set; }
     public string name { get; set; }
     //some more...
}

The WebMethod:

[WebMethod]
public List<DayEntryBT> getDayEntries()
{
    List<DayEntryBT> listOfEntries = new List<DayEntryBT>();
    //some sql...
    while (reader.Read()){
        DayEntryBT day = new DayEntryBT();
        DayEntryBT.date = reader["date"];
        day.name = reader["name"];
        listOfEntries.add(day);
    }
    return listOfEntries;
}

And the Javascript:

        $.ajax({
        type: "POST",
        url: "DataProviderBT.asmx/getDayEntries",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (resp) {
            alert(resp.d.date); //HOW TO GET THE STATIC ATTRIBUTE date HERE??????
            alert(resp.d[0].name); //THIS WORKS!!!
        }
    });

How can I get and set the value from the static attribute from javascript?

Regards


Solution

  • To workaround you can change your DayEntryBT class like this

    public class DayEntryBT{
        public static string StaticDate { get; set; }
        public string date {get { return StaticDate; }}
        public string name { get; set; }
        //some more...
    }
    

    and after you can get it like

    $.ajax({
        type: "POST",
        url: "DataProviderBT.asmx/getDayEntries",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (resp) {
            alert(resp.d[0].date); //this works, with value of static field
            ....
        }
    });
    

    also you can see about custom serializer.