0

This is my model :

 public class Stages
  {
      public int Id { get; set; }
      public string Code { get; set; }
      public string Name { get; set; }
      public string Des { get; set; }
      public string View_Count { get; set; }
  }

My Controller :

 public ActionResult ViewStages()
    {
        return View();
    }

And my view :

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 

Inherits="System.Web.Mvc.ViewPage<IEnumerable<Project.Models.Stages>>" %>

//Some Code...

<% foreach (var item in Model)
       { %>
    <tr>
        <td>
            <%: Html.DisplayFor(modelItem => item.Code)%>
        </td>
        <td>
            <%: Html.DisplayFor(modelItem => item.Name)%>
        </td>
        <td>
            <%: Html.DisplayFor(modelItem => item.Des)%>
        </td>
        <td>
            <%: Html.DisplayFor(modelItem => item.View_Count)%>
        </td>
        <td>
            <%: Html.ActionLink("Edit", "Edit", new { id = item.Id })%> |
            <%: Html.ActionLink("Details", "Details", new { id = item.Id })%> |
            <%: Html.ActionLink("Delete", "Delete", new { id = item.Id })%>
        </td>
    </tr>
<% }%>

</table>

</asp:Content>

And I always get this error : Object reference not set to an instance of an object. and the error occurred when it reaches the foreach loop. What is the problem?

1 Answer 1

2

Because you didn't initialize it

   public ActionResult ViewStages()
   {
        //this initialize your model
        var viewModel=new List<Stages>()       
                          {
                              new Stages()
                                  {
                                      Id = 1,
                                      Code = "any code",
                                      //etc
                                  }
                          }; 
        return View(viewModel);   //you have to pass the model to the view
     }
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! Thanks a lot Massimiliano

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.