0

i am creating a demo MVC project and i am getting a Null Object Reference error for the following code.

<% foreach (var item in Model) { %>
   <tr>
       <td>
           <%= Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) %> |
           <%= Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ })%> |
           <%= Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })%>
       </td>
       <td>
           <%= Html.Encode(item.ContactEmail) %>
       </td>
       <td>
           <%= Html.Encode(item.YourQuery) %>
       </td>
   </tr>
<% } %>

i get an error in the first line itself (var item in Model) coz i am getting the Model object as null.

Can anyone please help me.

thanks.

2
  • Do you use View(yourModelObject) as return in action method? Commented May 5, 2010 at 9:22
  • you should check first that your Model Object is null or not & if no then only foreach should get executed. Commented May 5, 2010 at 9:24

1 Answer 1

1

You should pass a model in your controller action:

public ActionResult Index()
{
    return View(new YourModel());
}
Sign up to request clarification or add additional context in comments.

2 Comments

hey buddy, appreciate your help but i am not getting my model name when i type "(new ...)". i have added a "SQL To Linq" class as my model named "ContactUs". Also i was trying out this code while watching a video online and they have not passed any model name in their code, but their project is running fine. hope you got it... thanks
hey buddy, i understood where the problem was. and thanks for the solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.