Why is my model null in the view?

I had created the Index action in my MVC controller. Nothing fancy, just something to get me started:

        public ActionResult Index() {
            Role role = new Role();
            role.Activities = new List<Activity>();
            role.Activities.Add(new Activity(1, "Run"));
            role.Activities.Add(new Activity(2, "Walk"));
            role.Activities.Add(new Activity(3, "Sprint"));
            return View();
        }

Then in my view, I did the simple action of looping through the activities:

@model Web.Models.RoleMode
@using (Html.BeginForm("New", "Roles", FormMethod.Post, new { @class="form-horizontal"})) {
    <h1>Roles</h1>
    foreach (var item in Model.Activities) {
        <p>hi</p>
    }
}

However, I was getting an “Object reference not set…” on the Model.

The problem was that I wasn’t passing the model from the controller to the view. See that last line in the controller:

      return View();

What I needed to do was add the model:

      return View(role);

That fixed it.

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: