【问题标题】:Controller.Json() returns nullController.Json() 返回 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?

标签: c# json asp.net-mvc model-view-controller


【解决方案1】:

更改您的视图模型以使用属性,而不是字段:

public class ExpensesViewModel
{
    public string Name { get; set; }
    public string Value { get; set; }
    public string Date { get; set; }
}

原因是默认模型绑定器使用公共 getter/setter 绑定到属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 2016-03-30
    相关资源
    最近更新 更多