How to list items per logged-in user in Asp.net MVC

Asked

Viewed 616 times

1

I have an application that manages Courses and I have the following problem, the pupil makes his enrollment in courses, only when the pupil access the page where lists the courses he is enrolled, this list is also listing the courses of other students, and not only the student who is logged.

I tried to do so

My Action controller’s 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());
    }

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 goal is to list only the courses of the student, use the properties of student navigation. Ie:

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 required because it is just a listing. There is no data persistence for this Action.

  • Apenar. HttpGet to request data query, HttpPost to request addition/creation of data, HttpPut to request data update and HttpDelete to request data deletion.

Browser other questions tagged

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