0

I'm only using ASP.Net and MVC, no other libraries. The code is the following:

//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;
}

The data that Json(list) returns is null, even though the list is not, I looked in the debugger, the connection to the DB is good, the data arrives, it is put into the list, but when I try and convert it to Json it fails. I've tried adding elements into the list manually, the Json function still returns null.

1
  • What version of mvc are you using? Commented Mar 11, 2021 at 12:26

1 Answer 1

2

Change your view model to use properties, not fields:

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

The reason is that the default model binder binds to properties with public getters/setters.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.