0

I want to send an empty list from the controller to the view, populate it, and then send it back to the controller. I'm unsure how to do this without creating this exception

System.NullReferenceException: 'Object reference not set to an instance of an object.

Basically my question is, how do I default the list in my model of be empty?

Model

public class AuditViewModel
{
    public string Domain { get; set; }
    public string Level { get; set; }
    public string NEWS { get; set; }
    public string Auditor { get; set; }
    public int PatientID { get; set; }
}

public class AuditDetail
{
    // I want to send this list as empty when page loads
    public List<AuditViewModel> AuditDetails { get; set; }
}

This is my controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        Models.AuditDetail ad = new Models.AuditDetail();
        return View(ad);
    }

    public ActionResult Audit()
    {
        return View();
    }
}

View

@{ int i = 0; foreach (var item in Model.AuditDetails.ToList()) }

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
Stu
  • 213
  • 2
  • 12
  • 1
    This could be answered by the canonical [What is an NullReferenceException](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it). However just write _public List AuditDetails { get; set; } = new List();_ – Steve Feb 05 '20 at 18:24
  • And you dont't need a _ToList()_ when you reference _Model.AuditDetails_ It is already a `List` – Steve Feb 05 '20 at 18:26
  • Thanks for the response - I still get System.NullReferenceException: 'Object reference not set to an instance of an object.' System.Web.Mvc.WebViewPage.Model.get returned null. – Stu Feb 05 '20 at 18:29
  • Probably because of `return View();` Does your view account for the fact that the model might be null? – Igor Feb 05 '20 at 18:35
  • Yes i have now done the following: Models.AuditDetail ad = new Models.AuditDetail(); return View(ad); – Stu Feb 05 '20 at 18:39
  • Thanks both. Igor i had not account for fact the model might have been null. Steve, i have read the link you sent me and also made the changes, it appears to be working now. Thanks – Stu Feb 05 '20 at 18:45

0 Answers0