Error in foreach

1

Good evening guys. I have a project for a school that records student data and its occurrences. going straight to my problem: What happens is that I have a page where 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 am calling it in the view Index of the Home controller, that even in it I made an action result to search in the table of occurrences all the occurrences that have in the system and show in that Partial. At the level of knowledge, this Home controller, has nothing, only renders a view with the options that each user can access depending on his profile. But what is happening to me is, in a certain profile, I want to log in, besides showing his options show this Partial with the occurrences, only that soon after the user was supposed to be shown the view Index and with her I am trying to render a partial, but I do not know how to do it. I am trying to do this, but I do not know how to do it. 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 that foreah that he alleges 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 }))
    
asked by anonymous 26.07.2014 / 01:22

1 answer

2

If I really understand, you simply want to render a Partial which is of type PagedList.IPagedList<CEF01.Models.Ocorrencia> in View Index.

So when you render your Partial (in this case in your View Index), you need to pass this as a parameter. This parameter will be the Model that the foreach of your 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, an example of how to Render a Partial View in Index:

Creating an Occurrence 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 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 this case will be the Model used in Partial) to your Partial View, otherwise an error will occur as I put it at the beginning of the response.

Ifit'sstillunclear,youhavea link here a> explaining too.

    
26.07.2014 / 04:52