How to bind an Id in ASP.NET MVC

1

Well, I have a little problem with my application, which is a Course Manager. The problem is that "student" has to enroll in some course, but I am not able to make the student's association to the course. In my registration screen I have a button "enrollment", where, the student clicks and this button should associate the "student" to that course, besides associating, this button also decreases the number of places for that course according to what the students are enrolling.

I'm trying to do this
Meu Controller

public ActionResult Inscricao(int? id)
    {
        using (var scope = new TransactionScope())
        {

            // Aqui pegaria o aluno logado.
            // E aqui é onde tenho que fazer a associação do aluno ao curso.

            Curso curso = new Curso();

            //Tentei fazer assim, mas não consegui
            curso = db.Cursos.Include(a => a.Aluno).AsNoTracking().FirstOrDefault(c => c.Id == id);

            curso.Qtd_Vagas--;
            db.Entry(curso).State = EntityState.Modified;
            db.SaveChanges();

            scope.Complete();
        }

        return View("Inscricao", db.Cursos.ToList());

    }
    
asked by anonymous 04.06.2015 / 19:39

1 answer

0

How I explained to you here , as the modeling has changed, what needs to be done is to create an association object between Aluno and Curso and then decrement the number of places of a Curso .

That is:

public ActionResult Inscricao(int? id)
{
    using (var scope = new TransactionScope())
    {

        // Aqui pegaria o aluno logado.
        var aluno = db.Alunos.FirstOrDefault(/* Aqui vai uma condição */);
        if (aluno == null) return View("Inscricao", db.Cursos.ToList());

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

        var alunoCurso = new AlunoCurso {
            Aluno = aluno, 
            Curso = curso}
        };

        db.AlunoCursos.Add(alunoCurso);
        db.SaveChanges();

        curso.Qtd_Vagas--;
        db.Entry(curso).State = EntityState.Modified;
        db.SaveChanges();

        scope.Complete();
    }

    return View("Inscricao", db.Cursos.ToList());
}
    
04.06.2015 / 22:02