【发布时间】:2021-06-09 10:11:56
【问题描述】:
我只使用 ASP.Net 和 MVC,没有其他库。 代码如下:
//ExpensesController.cs - the controller
public IActionResult getExpenses()
{
List<ExpensesViewModel> list = new List<ExpensesViewModel>();
string connectionString = "Data Source=DESKTOP-72RT825;Initial Catalog=AccountingDB;Integrated Security=True;Pooling=False";
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
SqlCommand query = new SqlCommand("Select * from Expenses", sqlConnection);
try
{
SqlDataReader reader;
reader = query.ExecuteReader();
while (reader.Read())
{
String name = reader.GetValue(0).ToString();
String value = reader.GetValue(1).ToString();
String date = reader.GetValue(2).ToString();
list.Add(new ExpensesViewModel() { Name = name, Date=date, Value = value });
Debug.Print(name + " " + " " + value);
}
}
catch (SqlException ex)
{
Debug.Print(ex.Message);
return Json(ex.Message);
}
JsonResult jsonResult = null;
try
{
jsonResult = Json(list);
}
catch(Exception ex)
{
Debug.Write(ex.Message);
}
return jsonResult;
}
//The View Model
public class ExpensesViewModel
{
public string Name;
public string Value;
public string Date;
}
Json(list)返回的数据是null,虽然list不是,我在调试器中查看,与DB的连接良好,数据到达,放入list,但是当我尝试将其转换为 Json 失败。我已经尝试手动将元素添加到列表中,Json 函数仍然返回 null。
【问题讨论】:
-
你用的是什么版本的mvc?
标签: c# json asp.net-mvc model-view-controller