Error in foreach

Asked

Viewed 340 times

1

Good evening guys. I have a project for a school that registers the student’s data and their occurrences. going straight to my problem: What happens is that I have a page to show the new occurrences that were generated in the system by a Partial that I created to show this type of data. This Partial I’m calling her in the Index view of the controller Home, which I even made an action result to search in the table occurrences all occurrences that have in the system and show in this Partial. At the knowledge level, this controller Home, has nothing, only renders a view with the options that each user can access depending on their profile. But what is happening to me is, in a certain profile, I want that when logging in, in addition to showing his options show this Partial with occurrences, only that soon after the logged in user was to be shown the Index view and next to it the Partial that I created, only that it returns me an error inside the foreach saying that it has no reference to the object, but if I try to render the partial alone, usually via link or via direct URL, it works and shows the data in a good... Could someone help me ?

Controller(Here I will show only Actionresult to speed up)

    private EntidadesContext db;
    public HomeController(EntidadesContext contexto)
    {
        this.db = contexto;
    }
    public ActionResult PartialOcorrencias(long? id, int? pagina)
    {
        List<Ocorrencia> resultado = db.Ocorrencias.Include(o => o.Aluno).ToList();

        int paginaTamanho = 25;
        int paginaNumero = (pagina ?? 1);
        var ocorrencias = resultado;

        return PartialView("PartialOcorrencias", ocorrencias.ToPagedList(paginaNumero, paginaTamanho));
    }

View(Home/Index)

       @using CEF01.Filters

        @{
             ViewBag.Title = "Olá";
                Verify.setVerify(Session[".PermissionCookie"].ToString());
         }

       <div class="container">
              <div class="jumbotron">
    <h2 class="text-center">Bem Vindo ao <i>Sistema de Gestão de Alunos - SGA</i></h2>
    <br />

    <article>
       <h3> Olá, @User.Identity.Name</h3>
    </article>

    @if (Verify.isProfessor())
    {
        @Html.Partial("_PartialProfessor")
    }
    else if (Verify.isCoordenador())
    {
        @Html.Partial("_PartialCoordenador")
        @Html.Partial("PartialOcorrencias")
    }
    else if (Verify.isAdmin())
    {
        @Html.Partial("_PartialProfessor")
        @Html.Partial("_PartialCoordenador")
        @Html.Partial("_PartialAdministrador")          
    }       

    <h3>Centro de Ensino Fundamental 01 - Riacho Fundo II</h3>
    </div>
  </div>

Partial(Partialocorrencias, and it is in this foreah that he claims the error)

@*@model IEnumerable<CEF01.Models.Ocorrencia>*@
@model PagedList.IPagedList<CEF01.Models.Ocorrencia>
 @using PagedList.Mvc;
  <link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
 <table>
<tr>
    <th>
        @*@Html.DisplayNameFor(model => model.Aluno.Nome)*@
        Nome do Aluno
    </th>
</tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Aluno.Nome)
            @Html.ActionLink("Resolver", "Edita", new { id = item.Id })                
        </td>
    </tr>        
}
</table>
 Pagina @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) de @Model.PageCount
 @Html.PagedListPager(Model, pagina => Url.Action("PartialOcorrencias", new { pagina, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

1 answer

2


If I really get it, you simply want to render a Partial who’s kind PagedList.IPagedList<CEF01.Models.Ocorrencia> in View Index.

So when do you render your Partial (in the case in your View Index), you need to pass this as parameter. This parameter will be the Model that the foreach of his Partial will iterate, can not be null, otherwise you will receive a Nullreferenceexception.

In your View Index we would have for example:

//ModelDaIndex.ListaDeOcorrencias ou o parâmetro que você for passar para a Partial
//não pode estar nulo, pois a Partial depende dele para ser populada
@Html.Partial("_PartialOcorrencias", ModelDaIndex.ListaDeOcorrencias)

Editing:

As a better explanation was requested, follow an example of how to Render a Partial View in the Index:

Creating a Occult class

public class Ocorrencia
{
    public string Descricao { get; set; }
}

Creating the index model with a list of occurrences

public class ModelDaIndex
{
    public ModelDaIndex()
    {
        ListaDeOcorrencias = PreencherListaDeOcorrencias();
    }

    //Propriedade com a lista de ocorrências
    public List<Ocorrencia> ListaDeOcorrencias { get; set; }

    //Método que apenas retorna uma lista de ocorrências
    public List<Ocorrencia> PreencherListaDeOcorrencias()
    {
        List<Ocorrencia> listaDeOcorrencias = new List<Ocorrencia>();
        listaDeOcorrencias.Add(new Ocorrencia()
        {
            Descricao = "Ocorrência 1"
        });
        listaDeOcorrencias.Add(new Ocorrencia()
        {
            Descricao = "Ocorrência 2"
        });
        return listaDeOcorrencias;
    }
}

Creating a Partial View to iterate over occurrences and list them in the Index view

@model Mvc4Application.Models.ModelDaIndex

@{
    ViewBag.Title = "_PartialOcorrencias";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Minha _PartialOcorrencias</h2>

@if (Model.ListaDeOcorrencias != null)
{     
    <table>            
        <tr>
            <th>
                Descrição
            </th>            
        </tr>
        @foreach (var ocorrencia in Model.ListaDeOcorrencias)
        {
            <tr>
                <td align="center">
                    @ocorrencia.Descricao
                </td>                                
            </tr> 
        }
    </table>
}

Creating the Index view with the helper to render the Partial View

@model Mvc4Application.Models.ModelDaIndex
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

Código e lógica da sua View Index....

Renderizando a Partial View:
<div>
    @Html.Partial("_PartialOcorrencias", Model)
</div>

Note that you need to pass a parameter (which in case will be the Model used in Partial) to your Partial View, otherwise an error will occur as I put at the beginning of the answer.

Adicionando parâmetro para usar na Partial

If it’s not clear yet, there’s a link here explaining also.

inserir a descrição da imagem aqui

  • I still don’t quite understand... Could you explain to me again ?

  • @Érikthiago edited the answer, I believe you will be able to understand.

  • now I could understand yes. But, I have a question: Why the need to create a model just for this ? Can I do this operation of showing all database data from a table in a Controller or a different View ? Because I already did a partial to show in the detail view (Students) beyond the student data its occurrences (so I created a partial to be rendered in this detail view). So what happens is: I rendered a partial with the student’s occurrences along with their data, that is, different data, but rendered together. I wanted to do it.

  • I decided here man ! Thanks for the help !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.