Home > Net >  .Net Core Web API Object naming
.Net Core Web API Object naming

Time:12-22

I'm new to API builds. I'm trying to design an API for datatables.js where I can pull and list data, but I couldn't design a structure suitable for using data tables. {data: [{ other data }]} I need to create an ordered list like this. But I couldn't find how to do it in .net core web API. I leave you images so that you can fully understand my problem.

I want this structure

As you can see in this image, other data is listed in a data object, and I want to do exactly that, but I couldn't find how to do it in .net core.

current structure

I'm trying to convert the structure you see in this image to the structure I want above.

CodePudding user response:

Since you didn't share your model classes code. I created C# classes based on the JSON structure and here is the result.

public class DataResponse
{
    [JsonPropertyName("data")]
    public List<Item> Data { get; set; } = null!;
}

public class Item
{
    [JsonPropertyName("id")]
    public int Id { get; set; }

    [JsonPropertyName("ad_soyad")]
    public string? AdSoyad { get; set; }

    [JsonPropertyName("il")]
    public string? Il { get; set; }

    [JsonPropertyName("ilce")]
    public string? Ilce { get; set; }

    [JsonPropertyName("kart")]
    public string? Kart { get; set; }

    [JsonPropertyName("rfid")]
    public string? RfId { get; set; }

    [JsonPropertyName("durum")]
    public string? Durum { get; set; }
}

Next, you can create an instance of the DataResponse object and Data property, then return it, like this.

var result = new DataResponse()
{
    Data = new List<Item>()
    {
        new Item()
        {
            Id = 1,
            AdSoyad = "Ad Soyad",
            Il = "İl",
            Ilce = "İlçe",
            Kart = "Kart",
            RfId = "RfId",
            Durum = "Durum"
        },
        new Item()
        {
            Id = 2,
            AdSoyad = "Ad Soyad",
            Il = "İl",
            Ilce = "İlçe",
            Kart = "Kart",
            RfId = "RfId",
            Durum = "Durum"
        },
    }
};
return Json(result);

And you get results like this.

JSON Response

CodePudding user response:

  public IActionResult Get()
    {
        var data = db.Kullanicilars.ToList();

        var result = new DataResponse()
        {
            Data = new List<Kullanicilar>()
            {
        new Kullanicilar()
    {
        KullaniciId = 1,
        AdSoyad = "",
        Il = "",
        Ilce = "",
        Eposta = "",
        Telefon = "",
        Kart = "",
        Rfid = "",
        Durum = 1
    },

}
        };
        return Json(result);
    }

So how can I fill in the list you saw in the vaccine according to the model data I pulled from my database? I want it to be like foreach logic, so that for each new data, a new new users open the list and add it. How can I do that?

  • Related