Decrement in an ASP.NET MVC table field

2

I'm developing course manager in asp.net MVC , and the course table has a qtd_vagas field. I would like to know how I can do a count - ( or some other form of Decrement ) this field. For example: In the list of courses will appear the courses and the number of places and a button to enroll. The student clicking on the qtd_vagas field will decrease the number of places in the table and on the screen. Courses with 50 vacancies, if an enrollment is made it will decrease 49, 48, 47 ... How do I make the field automatically update both table and user screen!?

    
asked by anonymous 19.05.2015 / 05:45

1 answer

0

I'm assuming you're using Entity Framework to abstract the database. An example of Action in Controller would look something like this:

public ActionResult Inscrever(int id) // Este id é o id do curso
{
    // Aqui penso que ocorreria uma seleção do aluno logado.
    // Depois uma associação do aluno ao curso.
    // Suponho que o curso seria colocado em uma variável "curso".
    curso.QuantidadeVagas--;
    context.Entry(curso).State = EntityState.Modified;
    context.SaveChanges();
    return RedirectToAction("AlgumaAction", "AlgumController");
}

Just as there are various bank operations you do here (select student, select course, create association, modify course), I recommend you use transactional scope . Here it would look like this:

public ActionResult Inscrever(int id) 
{
    using (var scope = new TransactionScope()) 
    {
        // Aqui penso que ocorreria uma seleção do aluno logado.
        // Depois uma associação do aluno ao curso.
        // Suponho que o curso seria colocado em uma variável "curso".
        curso.QuantidadeVagas--;
        context.Entry(curso).State = EntityState.Modified;
        context.SaveChanges();

        scope.Complete(); 
    }

    return RedirectToAction("AlgumaAction", "AlgumController");
}

For on-screen viewing, it's trivial: updating the course value will reflect the presentation automatically:

@model Curso

<h1>Quantidade de Vagas: @Model.QuantidadeVagas</h1>

An example of Ajax would be a button like this:

<button id="decremento" name="1">Decrementar</button>

Add jQuery to your Views ( search for Bundling ) and type something like this:

<script>
    $(document).ready(function() {
        $("#decremento").click(function() {
            $.ajax({
              type: "POST",
              url: '/MeuController/Inscrever/' + $(this).attr("name")
            });
        });
    }); 
</script>
    
19.05.2015 / 05:54