简体   繁体   中英

How to get values from object in c#

my Json code is

ListOrderDetails.push({ // Add Order Details to array                  
                "OrderType": OrderType,
                "CaseNumber": CaseNumber,
                "OrderNumber": OrderNumber,
                "OrderStatus": OrderStatus,
                "Reason": Reason,
                "Coments": Coments
            });

var Params = { "Geo": Geography, "GeoId": GeographyID, "CountryCode": CountryCode, "Segment": Segment, "SubsegmentID": SubSegmentID, "OrderDetails": ListOrderDetails };
        //var Params = { "Geo": Geography, "GeoId": GeographyID, "CountryCode": CountryCode, "Segment": Segment, "SubsegmentID": SubSegmentID };
        $.ajax({
            type: "POST",
            url: "MyDataVer1.aspx/SaveManualEntry",
            contentType: "application/json",
            data: JSON.stringify(Params),
            dataType: "json",
            success: function(response) {
                alert(response);
            },
            error: function(xhr, textStatus, errorThrown) {
                alert("xhr : " + xhr);
                alert("textStatus : " + textStatus);
                alert("errorThrown " + errorThrown);
            }
        });

c# webmethod is

[WebMethod]
public static int SaveManualEntry(string Geo, int GeoId, string CountryCode,
                                  string Segment, string SubsegmentID, 
                                  object[] OrderDetails)
{

    try
    {
        int TotalOrderCount = 0;
        int Successcount = 0;               
        return Successcount;

    }
    catch (Exception ex)
    {
        throw ex;
    }

}

How to get values from the Object orderDetails. I cant use indexing.

You first need to create an order detail object:

public class OrderDetail
{
    public string OrderType { get; set; }
    public string CaseNumber { get; set; }
    public string OrderNumber { get; set; }
    public string OrderStatus { get; set; }
    public string Reason { get; set; }
    public string Coments { get; set; }
}

Then change your web method to this:

[WebMethod]
public static int SaveManualEntry(string Geo, int GeoId, string CountryCode,
                                  string Segment, string SubsegmentID, 
                                  List<OrderDetail> OrderDetails)
{

    try
    {
        int TotalOrderCount = 0;
        int Successcount = 0;               
        return Successcount;

    }
    catch (Exception ex)
    {
        throw ex;
    }

}

Which accepts a List<OrderDetails> instead.

You can use reflection:

foreach(var order in orderDetails)
{
    string orderType = (string)order.GetType().GetProperty("OrderType").GetValue(order);
    // other properties
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM