Home > Blockchain >  ASP.NET MVC View is showing NULL
ASP.NET MVC View is showing NULL

Time:12-03

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();
    }

CodePudding user response:

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)

  • Related