psj01
psj01

Reputation: 3245

Why am I getting a null reference exception when rendering this razor view?

I am following along an mvc tutorial on udemy and I am getting an null reference error. when I try to get Model.Name

I am not sure what Im doing wrong here.. I have the code exactly the same was as explained in the tutorial.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vidly.Models;

namespace Vidly.Controllers
{
    public class MoviesController : Controller
    {
        // GET: Movies/Random
        public ActionResult Random()
        {
            var movie = new Movie() { Name="Shrek" };

            return View();
        }
    }
}

My view has :

@model Vidly.Models.Movie

@{
    ViewBag.Title = "Random";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>@Model.Id</h2>

enter image description here

Upvotes: 1

Views: 1913

Answers (3)

Hasta Tamang
Hasta Tamang

Reputation: 2263

You forgot to pass your model to the view.

return View(movie);

Upvotes: 1

Fran
Fran

Reputation: 6520

You haven't passed your model to the View.

public class MoviesController : Controller
{
    // GET: Movies/Random
    public ActionResult Random()
    {
        var movie = new Movie() { Name="Shrek" };

        //important line
        return View(movie);
    }
}

Upvotes: 1

Nick Heidke
Nick Heidke

Reputation: 2847

You need to pass your model back to the view:

return View(movie);

Upvotes: 7

Related Questions