简体   繁体   中英

MVC Null Reference on Model

I'm trying to implement a partial view but I'm having troubles with the model. I'm getting the following error:

System.NullReferenceException: object reference not set to an instance of an object

The HTML code where the error is detected is the following:

@model IEnumerable<BUGTRACKER.Models.Revisiones>


<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Version)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Descripción)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Fecha)
    </th>
    <th></th>
</tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Version)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Descripción)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Fecha)
        </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>
}

I really don't know what's going on here, any idea?

EDIT: This is my action

public ActionResult _Index()
{
    return PartialView(db.Revisiones.ToList());
}

@levelnis approach did it!

Try using Html.Action instead of Html.Partial to render the partial.

This worked for me.

From the Viewmodel you are returning List<BugTracker.Models.Revisiones> List, in the view as well the type of Model is correct.

But you are trying to access the properties that are in the ViewModel and not in the List iterator.

Version, Description, Fecha are not part of BugTracker.Models.Revisiones class I suppose.

Solution would be to return the RevisonesViewModel from ViewModel


    public ActionResult _Index()
    {
        return PartialView(object of RevisonesViewModel);
    }

instead of


    public ActionResult _Index()
    {
        return PartialView(db.Revisiones.ToList());
    }

Your Model is an IEnnumerable of BUGTRACKER.Models.Revisiones

When you iterate it's ok since it's a list.

However, you can not do this: model.Version since it doesNot exist in your model. What you need is a model that encapsulate your properties and a list of BUGTRACKER.Models.Revisiones.

Public Class RevisonesViewModel{
      public string Version{ get; set; }
      public string Fetch{ get; set; }
      public string Description{ get; set; }
      public IEnumerable<BUGTRACKER.Models.Revisiones> MyRevisiones
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM