-1

As the title says, im getting that error when trying to get the value out of an user object to be displayed. Im using Entity Framework Code-First, so all the Models are generated, im trying to combine multiple tables with eachother. "Displaying all users with their project data and flextime" (Now flextime is just a decimal)

Model:

    public class ListModel
{
    public List<StaffModel> StaffModelList { get; set; } 
}

    public class StaffModel
{
    public FlexModel Flex { get; set; }
    public List<string> ProjectName { get; set; }
}

    public class FlexModel
{
    public User User { get; set; }
    public decimal FlexTime { get; set; }
}

View:

@model Aviato.ViewModel.ListModel 

<table class="table">
@foreach (var item in Model.StaffModelList)
    {
        <tr>
            <td>@item.Flex.User.UserId</td>
            <td>@item.Flex.FlexTime</td>
            <td>@item.ProjectName</td>
            <td>@item.Flex.User.SocialSecurityNumber</td>
            <td>@item.Flex.User.FirstName</td>
            <td>@item.Flex.User.LastName</td>
            <td>@item.Flex.User.Address1</td>
            <td>@item.Flex.User.ZipCode</td>
            <td>@item.Flex.User.City</td>
            <td>@item.Flex.User.PhoneNumber1</td>
            <td>@item.Flex.User.EmploymentStartDate</td>
            <td>@item.Flex.User.Password</td>

            @foreach (var project in item.ProjectName)
            {
                <td>@project</td>
            }

            @Html.ActionLink("Redigera", "Edit", new { id = item.Flex.User.UserId })
            @Html.ActionLink("Ta bort", "Delete", new { id = item.Flex.User.UserId })
        </tr>
       }
</table>

Controller:

private readonly AviatoModel _db = new AviatoModel(); //Database

public ActionResult Index()
    {
        var projects = _db.Projects.ToList();
        var users = _db.Users.ToList();
        var model = new ListModel();

        model.StaffModelList = new List<StaffModel>();

        foreach (var u in users)
        {
            var flexModel = new StaffModel();
            flexModel.Flex.User = u; //This is where the Error occurs.
            flexModel.Flex.FlexTime = GetFlex.Flex(u.UserId);
            model.StaffModelList.Add(flexModel);
        }

        return View(model);
    }

Please help.

Qvadriologic
  • 85
  • 1
  • 2
  • 8

1 Answers1

2

The Flex property of StaffModel is never instantiated so when you try to access a method on it, you get the NullReferenceException. Add a constructor to your class like this to create it as an empty object:

public class StaffModel
{
    public StaffModel()
    {
        Flex = new FlexModel();
    }

    //snip
}
Hans Kesting
  • 34,565
  • 7
  • 74
  • 97
DavidG
  • 95,392
  • 10
  • 185
  • 181