Controller.Json() 返回 null
Posted
技术标签:
【中文标题】Controller.Json() 返回 null【英文标题】:Controller.Json() returns null 【发布时间】: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? 【参考方案1】:更改您的视图模型以使用属性,而不是字段:
public class ExpensesViewModel
public string Name get; set;
public string Value get; set;
public string Date get; set;
原因是默认模型绑定器使用公共 getter/setter 绑定到属性。
【讨论】:
以上是关于Controller.Json() 返回 null的主要内容,如果未能解决你的问题,请参考以下文章
为啥 WCF/JSON 不为 null 返回值返回“null”?
places.getLatLng() 返回 null 虽然 places.getName() 没有返回 null