我想使用 asp.net mvc5 c# 從我的資料庫中回傳 JSON 格式。我嘗試了很多方法,但無法按照我的要求生成資料。我需要這種格式的 JSON 陣列。
{
"draw":0,
"recordsTotal":2,
"recordsFiltered":2,
"data":[
[
"126",
"Test Name 1",
"07.01.2022 11:55 AM",
"Male"
],
[
"127",
"Test Name 2",
"01.02.2022 11:55 AM",
"Male"
]
]
}
而不是這個,我得到給定格式的輸出
{
"draw":0,
"recordsTotal":2,
"recordsFiltered":2,
"data":[
{
"ID":126,
"Name":"Test Name 1",
"Date":"07.01.2022 11:55 AM",
"Gender":"Male"
},
{
"ID":127,
"Name":"Test Name 2",
"Date":"01.02.2022 11:55 AM",
"Gender":"Male"
}
]
}
我的 ASP.NET MVC5 C# 代碼如下
public ContentResult GetDoctor()
{
var doctors = db.Doctors.Where(e => e.ID > 0);
var doct = doctors.Select(c => new
{
ID = c.ID ","
"," c.Name
"," c.Date
"," c.Gender
}).ToList();
string students = string.Join("],[", doct.Select(e => e.ID.ToString()));
students = JsonConvert.SerializeObject(students);
JsonSerializerSettings hg = new JsonSerializerSettings();
hg.Formatting = Formatting.Indented;
hg.TypeNameHandling = TypeNameHandling.None;
string json = JsonConvert.SerializeObject(doctors.ToList(),hg);
return Content(json.ToString(), "application/json");
}
uj5u.com熱心網友回復:
如果需要嚴格使用第一個結構體回傳資料,那么輸出結構體必須是:
public class Required_Result
{
[JsonProperty("draw")]
public int Draw { get; set; }
[JsonProperty("recordsTotal")]
public int RecordsTotal { get; set; }
[JsonProperty("recordsFiltered")]
public int RecordsFiltered { get; set; }
[JsonProperty("data")]
public List<List<string>> Data { get; set; }
}
然后我想你從資料庫中恢復的資料是第二種格式:
public class Doctors_data
{
[JsonProperty("ID")]
public int ID { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Date")]
public string Date { get; set; }
[JsonProperty("Gender")]
public string Gender { get; set; }
}
public class Resume
{
[JsonProperty("draw")]
public int Draw { get; set; }
[JsonProperty("recordsTotal")]
public int RecordsTotal { get; set; }
[JsonProperty("recordsFiltered")]
public int RecordsFiltered { get; set; }
[JsonProperty("data")]
public List<Doctors_data> Data { get; set; }
}
所以你需要將你的資料轉換成需要的結果格式資料并反序列化
Resume db = new Resume(); //<--- Populate your data
Required_Result result = new Required_Result()
{
Draw = db.Draw,
RecordsTotal = db.RecordsTotal,
RecordsFiltered = db.RecordsFiltered,
Data = db.Data.Where(e => e.ID > 0).Select(item => new List<string> { item.ID.ToString(), item.Name, item.Date, item.Gender }).ToList()
};
string result_string = JsonSerializer.Serialize(result);
uj5u.com熱心網友回復:
您可以使用以下方法:
return Json(new
{
draw = draw,
recordsFiltered = recordsTotal,
recordsTotal = recordsTotal,
data = doctors
});
從 UI獲取繪制值。像這樣 :
var draw = Request.Form.GetValues("draw").FirstOrDefault();
醫生是你的名單。
記錄號的值也是從串列中的資料個數中獲取的。
有了這個答案,您可以將資料發送到 UI 并將其加載到datatable中。
我在我的專案中使用這個標準并且它有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/414360.html
標籤:
上一篇:字串拆分c#但忽略某些情況
下一篇:組合框的默認值未在部分視圖中分配
