How to list items per logged-in user in ASP.NET MVC

1

I have an application that manages Courses and I have the following problem, student makes your enrollment in courses >, but when the student accesses the page where they list the courses they are enrolled in, this list is also listing other students' courses , and not only or the student who is logged in .

I tried to do this

My Action of controller Curso

public ActionResult MeusCursos()
    {
        Aluno aluno = db.Alunos.FirstOrDefault(a => a.Usuario == User.Identity.Name);
        if (aluno != null)
            return View("MeusCursos", db.Cursos.ToList());

        return View();

    }

Post

[HttpPost]
    public ActionResult MeusCursos(int id)
    {
        Aluno aluno = db.Alunos.FirstOrDefault(a => a.Usuario == User.Identity.Name);
        if (aluno != null)
            return View("MeusCursos", db.Cursos.ToList());

        var curso = db.Cursos.FirstOrDefault(c => c.Id == id);
        if (curso == null)
            return View("MeusCursos");


        return View(db.Cursos.ToList());
    }
    
asked by anonymous 24.06.2015 / 07:28

1 answer

3

This is obviously wrong:

Aluno aluno = db.Alunos.FirstOrDefault(a => a.Usuario == User.Identity.Name);
if (aluno != null)
    return View("MeusCursos", db.Cursos.ToList());

Here:

db.Cursos.ToList()

You are bringing all the courses. If the purpose is to list only the student's courses, use the student navigation properties. That is:

Aluno aluno = db.Alunos.FirstOrDefault(a => a.Usuario == User.Identity.Name);
if (aluno != null)
    return View("MeusCursos", aluno.AlunoCursos.Select(ac => ac.Curso).ToList());

The method with [HttpPost] is not necessary because it is just a listing. There is no data persistence for this Action .

    
24.06.2015 / 07:38