0

I have a follow up question on the accepted answer given here: Two models in one view in ASP MVC 3

I have three models, Types, Causes, Locations that I would like to list the contents of in one view. Based on the answer in the link above I made a new model that combined the that looks like this:

public class Combined
    {
        public IEnumerable<Place> Place { get; set; }
        public IEnumerable<Type> Type { get; set; }
        public IEnumerable<Cause> Cause { get; set; }
    }

I made it IEnumerable<> because as I understand it, thats what I want when I just want to list the contents of these models in a foreach loop. Then I made this controller for the view:

[ChildActionOnly]
    public ActionResult overSightHeadings()
    {
        Combined Combined = new Combined();
        return View(Combined);
    }

And finally the view (I was just trying to list from one of the tables first):

@model mvcAvvikelser.Models.Combined
@{
    Layout = null;
}
<tr>
@foreach (var Type in Model.Type)
{
    <th> @Html.DisplayTextFor(ModelItem => Type.Name)</th>
}
</tr>

The problem with this code is that it throws up a null exception when the foreach code starts.

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

So I am not entirely sure what I am doing wrong here, should it not be an IEnumerable, have I initialized the model incorrectly in the controller?

Community
  • 1
  • 1
Dennis
  • 373
  • 1
  • 6
  • 21

2 Answers2

1

Should be this

[ChildActionOnly]
public ActionResult overSightHeadings()
{
    Combined combined = new Combined();
    combined.Types = new List<Type>();
    combined.Causes = new List<Cause>();
    combined.Places = new List<Place>();

    return View(Combined);
}

Note that I have changed the property names to plural. That defines your property as collection.

codingbiz
  • 26,179
  • 8
  • 59
  • 96
  • Thanks this seems to work, it does not throw an error at least. The view does not seem to return any results though. – Dennis Sep 19 '12 at 08:17
  • You need to assign values to them. Now they are empty. Where are you getting those values from? Get those values and assign them instead of `new List()` – codingbiz Sep 19 '12 at 08:20
  • Aah yes ofcourse. It makes sense now that you explained it. I retrieve the values from a database and I replaced the new List() with the proper "connections" and now it works as it should :) – Dennis Sep 19 '12 at 08:30
0

looks like the

 public IEnumerable<Type> Type { get; set; }

is not set

try to initialize this list in model constructor whith no IEnumerable like

 List<Type> Type = new List<Type>();
maxs87
  • 2,274
  • 2
  • 19
  • 23