2
I am developing an application that manages Courses in Asp.net MVC, I’m still a beginner, and I’m trying to do the following: The Student has a screen where he lists all the courses for him to choose and make his enrolment in any of these courses. This part I’ve done, however, I need to do the following control, where, if this student enroll in a course, for example, information systems, he will not be able to enroll in it course because it is already enrolled, the system should bar and not let him make two entries in the same course.
My Action Registration
// GET
public ActionResult Inscricao()
{
//Aqui eu pego o Aluno logado
Aluno aluno = db.Alunos.FirstOrDefault(a => a.Usuario == System.Web.HttpContext.Current.User.Identity.Name);
if (aluno == null)
return View("MeusCursos");
//Aqui ficaria a parte onde verifica se o aluno já está inscrito em algum curso
return View(db.Cursos.ToList());
}
[HttpPost]
public ActionResult Inscricao(int inscricaoId)
{
using (var scope = new TransactionScope())
{
//Aqui eu pego o Aluno logado
Aluno aluno = db.Alunos.FirstOrDefault(a => a.Usuario == System.Web.HttpContext.Current.User.Identity.Name);
if (aluno == null)
return View("MeusCursos");
//Aqui ficaria a parte onde verifica se o aluno já está inscrito em algum curso
var curso = db.Cursos.FirstOrDefault(c => c.Id == inscricaoId);
if (curso == null)
return View("MeusCursos");
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(db.Cursos.ToList());
}
Can someone give me a hand in this case?
I took the test here @Gypsy, but still manage to enroll in a course I was already enrolled in.
– Novato
It worked @Gypsy, I had forgotten if. How do I display a message to the Student that he is already subscribed?
– Novato
@Newbie You can use
ModelState.AddModelError("", "Aluno já está inscrito no curso.");
. The message will appear where it is marked with@Html.ValidationSummary()
.– Leonel Sanches da Silva