-5

Ok, I saw a few similar questions regarding this. But I was unable to cobble together an answer to solve my particular problem.

Basically, I'm attempting to get data from SQL Server to print it onto a view (simple, right?). The problem is: I have a number of other things happening on the view. So, I have to use one model (I think).

Here is what I have (I am very (very very very) new to ASP.NET MVC):

Model

Here are the pref I'm attempting to write to (the model/class is Registrar)

//display props
public string QUID_Disp { get; set; }
public string QU_User_Disp { get; set; }
public string Admin_User_Disp { get; set; }
public string Reg_User_Disp { get; set; }

public List<Registrar> Events { get; set; }

Here is my SQL call in the controller

if (sqlStuff.Admin == "Yes")
{
    Registrar users = new Registrar();

    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["internet"].ConnectionString))
    {
        con.Open();

        using (SqlCommand da = new SqlCommand("select * from Registrar_Tool_Users", con))
        using (SqlDataReader reader = da.ExecuteReader())
        {
            while (reader.Read())
            {
                users.Events.Add (new Registrar { QU_User_Disp = reader["QU_User"].ToString(), QUID_Disp = reader["QUID"].ToString(), Admin_User_Disp = reader["Reg_Admin"].ToString() });
            }

            return View(users.Events);
        }
    }

And view:

@model QUTools.Models.Registrar
//Things that are working here......
@{

    foreach (var item in Model.Events)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.QU_User_Disp)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.QUID_Disp)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Admin_User_Disp)
            </td>
        </tr>
    }
}

The error occurs on the line

users.Events.Add (new Registrar...

and says:

An exception of type 'System.NullReferenceException' occurred in QUT.dll but was not handled in user code

tiermann
  • 15
  • 6
  • If that's where the error is, then it's nothing to do with MVC. You will get an error after this as the data passed to the view (list of events) does not match the view model (Registrar). For your SQL error, have a look at this: http://stackoverflow.com/help/mcve specifically the minimal part (eg, the view code is irrelevant for this error) - try moving the data load into its own method (or even class/data tier) to separate the data loading from the data viewing so you can see where the error occurs (in the data loading) – freedomn-m Jan 08 '16 at 15:06
  • 2
    I have an idea: learn how to debug your code. – Camilo Terevinto Jan 08 '16 at 15:10
  • hey Ramiamilu--ah doesn't seem to go through. still getting the null value. I ran the sql cmd and it pulled a number of vals, none are null. – tiermann Jan 08 '16 at 15:15
  • Hey frozen, real nice... – tiermann Jan 08 '16 at 15:16
  • initialize - `users.Events = new List();` – ramiramilu Jan 08 '16 at 15:17

1 Answers1

1

You are calling the Add() method on a property which is NULL. Add() method works on a non-null collection.So you need to initialize the Events collection to an empty collection before calling the Add() method.

You can do that in your view model class's constructor.

public class Registrar
{
   public string QUID_Disp { get; set; }
   public string QU_User_Disp { get; set; }
   public string Admin_User_Disp { get; set; }
   public string Reg_User_Disp { get; set; }
   public List<Registrar> Events { get; set; }

   public YourViewModel()
   {
     Events = new List<Registrar>();
   }
}

OR whenever you create an object of Registrar.

Registrar users = new Registrar();
users.Events=new List<Registrar>();

Or

Registrar users = new Registrar { Events=new List<Registrar>() };

I also recommend renaming your property/class names to something more readable. Looks like you have a Registrar class which has a property called Events, but it is again a list of Registrar. It is a good idea to name your view model in such a way that it explains what this view model/it's properties is for. For example

public class UserWithEventsVm
{
  public string DisplayName {set;get;}
  public List<EventVm> Events {set;get;}
  //Add other properties as needed by the view

  public UserWithEventsVm()
  {
    Events=new List<EventVm>();
  }
}
public class EventVm
{
  public int Id {set;get;}
  public string EventTitle {set;get;} 
}
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • I'm sorry, Shyju. I haven't worked with lists before (this is my first attempt at an MVC project). Your code helped me with the Null error. but now I keep getting the error _The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[QUTools.Models.Registrar]', but this dictionary requires a model item of type 'QUTools.Models.Registrar'._ -- I don't really understand the error because aren't the items i'm passing into the list the type qutools.models.registrar? it seems to be happening in the view. – tiermann Jan 08 '16 at 16:08
  • How does your GET action looks like ? You should be passing a single object of `Registrar` – Shyju Jan 08 '16 at 16:09
  • I'm not sure what you mean. But, I'm passing the object `users.Events` and in the view using `foreach (var item in Model.Events)` then attempting to display the data like this: `@Html.DisplayFor(m => item.QU_User_Disp)` – tiermann Jan 08 '16 at 16:17
  • If you are passing `users.Events` from your action method to your View, your view should be strongly typed to List and you should use `foreach(var item in Model)` to loop through it. – Shyju Jan 08 '16 at 16:18
  • Okay i get it. So, i got the list up and running! Thank you, so much. I can rework the other part of the view to work around this. the `@Html.TextBoxFor(m => m.QU_User)` (which are other pref in the model) don't work but i think I can make it work. :) thanks so much, again – tiermann Jan 08 '16 at 16:34
  • 1
    Yep--working perfectly. Thanks again, Shyju! – tiermann Jan 08 '16 at 16:51