Reputation: 3245
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>
Upvotes: 1
Views: 1913
Reputation: 2263
You forgot to pass your model to the view.
return View(movie);
Upvotes: 1
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
Reputation: 2847
You need to pass your model back to the view:
return View(movie);
Upvotes: 7