Search This Blog

Tuesday, December 3, 2013

@foreach (var item in Model), Object reference not set to an instance of an object in MVC Razor View

Index.cshtml

@model IEnumerable<RazorEngineMVC.Models.User>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th></th>
        <th>
            FirstName
        </th>
        <th>
            LastName
        </th>
        <th>
            EMail
        </th>
        <th>
            Address
        </th>
        <th>
            PhoneNo
        </th>
        <th>
            Company
        </th>
        <th>
            Designation
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        ….


Controller

public class MyController : Controller
    {
        //
        // GET: /My/

        public ActionResult Index()
        {
            return View();
        }
When you run the application it’s throwing as “Object reference not set to an instance of an object.” At below location
@foreach (var item in Model) {

Resolution for the above problem is change the implementation of Controller class like below

public class MyController : Controller
    {
        //
        // GET: /My/

        public ActionResult Index()
        {
//return View();
            return View(new List<Models.User>());
        }

Change the Index.cshtml like below

From
@model IEnumerable<RazorEngineMVC.Models.User>
To
@model List<RazorEngineMVC.Models.User>

No comments:

Popular Posts