0

I have a Controller that I have hard coded some values and expect the values to populate the 2 models with the data. However, there is one Model that is null when I run through the controller. Here are some snippets of the app.

When I run the code, Orders is null. I would expect there be 3 entries in customer orders but that is null.

CustomerOrderModel.cs:

public class CustomerOrderModel
{
    public int OrderId { get; set; }
    public DateTime OrderDate { get; set; }
    public string Description { get; set; }
    public decimal Total { get; set; }
}

CustomerViewModel.cs:

public class CustomerViewModel
{
    public int CustomerNumber { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName
    {
        get { return FirstName + " " + LastName; }
    }
    public List<CustomerOrderModel> Orders { get; set; }
}

Controller.cs:

public IActionResult Orders()
{
    decimal iTotal = 55.23M;
    CustomerViewModel customer = new CustomerViewModel();
    List<CustomerOrderModel> orders = new List<CustomerOrderModel>();

    try
    {
        for (int i = 1; i < 4; i++)
        {
            var order = new CustomerOrderModel();
            customer.CustomerNumber = 111111;
            customer.FirstName = "John";
            customer.LastName = "Smith";

            order.OrderId = i;
            order.OrderDate = DateTime.Now;
            order.Description = "Part " + i;
            order.Total = iTotal;
            iTotal += order.Total;

            orders.Add(order);
        }
        
        return View(customer);
    }
    catch (Exception)
    {
        return View("Error");
    }
}

customer object

orders object

I have tried to re-code the IActionResult Orders() without any luck. customer.Orders gives me no members.

Re-code Orders

public IActionResult Orders1()
{
    decimal iTotal = 55.23M;
    List<CustomerOrderModel> orders = new List<CustomerOrderModel>();

    for (int i = 1; i < 4; i++)
    {
        CustomerViewModel customer = new CustomerViewModel();
        customer.Orders = new List<CustomerOrderModel>();
        customer.CustomerNumber = 111111;
        customer.FirstName = "John";
        customer.LastName = "Smith";
    }
    return View();
}
2

1 Answer 1

1

In the public IActionResult Orders() action method set the Orders property value before render the view:

customer.Orders = orders; 
return View(customer);

The reference type default value is null and this what you see.


Default values of C# types (C# reference)

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.