Doubt with Viewdata using Asp.net core 2

Asked

Viewed 62 times

3

I made an example for testing using Viewdata, apparently it should work, but it is generating me a reference error, as message below.

The type or namespace name 'Student' could not be found

I made a reference to Ilist and Ienumerable and it doesn’t work, I’d appreciate it if someone could tell me some solution.

On my controller I have:

//classe aluno
public class Aluno
{
  public string Nome { get; set; }
  public double Idade { get; set; }
}

//action resulte para teste
public IActionResult About()
{
    ViewData["Message"] = "Your application description page.";
    IList<Aluno> alunos = new List<Aluno>();
    alunos.Add(new Aluno { Nome = "Marcos", Idade = 5 });
    alunos.Add(new Aluno { Nome = "Paulo", Idade = 10 });
    alunos.Add(new Aluno { Nome = "Maria", Idade = 15 });
    ViewData["RecebeAluno"] = alunos;
    return View();
}

In view I have:

@foreach (var p in ViewData["RecebeAluno"] as List<Aluno>)
{
    <ul>
        <li>@p.Nome</li>
        <li>@p.Idade</li>
    </ul>
}
  • Within your View you need to do the using of namespace of the Student or put the reference with full path. Could add in the question the namespace complete of the Student class, so I can illustrate?

  • @Barbetta, perfect your answer, worked perfectly

1 answer

3


As the message says "The type or namespace name 'Student' could not be found", the Student type or namespace could not be found. To use an object within the view it is necessary to either put the full path or the using.

@using SuaAplicaCao.Models


@foreach (var p in ViewData["RecebeAluno"] as List<Aluno>)
{
    <ul>
        <li>@p.Nome</li>
        <li>@p.Idade</li>
    </ul>
}

Or

@foreach (var p in ViewData["RecebeAluno"] as List<SuaAplicaCao.Models.Aluno>)
{
    <ul>
        <li>@p.Nome</li>
        <li>@p.Idade</li>
    </ul>
}

Browser other questions tagged

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