Prevent the user from voting on the same Post

0

I created a voting system, where users can give like / dislike in chapters of books posted on the site. Here is my action:

     public ActionResult Like(int id)
        {
            int iduser = Convert.ToInt32(Session["IDUsuario"]);
            Voto v = new Voto();

            if (iduser != 0)
            {
                v.IdUsuario = iduser;
                v.IdCapitulo = id;
                v.Voto1 = true;
                db.Voto.Add(v);
                db.SaveChanges();
                return RedirectToAction("Exibir","Capitulos");

}

            return View();

public ActionResult Dislike(int id)
        {
            int iduser = Convert.ToInt32(Session["IDUsuario"]);
            Voto v = new Voto();

            if (iduser != 0)
            {
                v.IdUsuario = iduser;
                v.IdCapitulo = id;
                v.Voto1 = false;
                db.Voto.Add(v);
                db.SaveChanges();
                    return RedirectToAction("Exibir","Capitulos");
            }


            return View();

However, I want to prevent the user from voting in the same chapter several times. Where, and how could I do this verification?

    
asked by anonymous 06.11.2014 / 04:11

2 answers

3

You could create a flag (Boolean variable) to mark if that user has already voted in this chapter. For this you would have to create a new table that stores the User ID and a chapter ID, every time the user votes you write to that table. The next time the user votes, you check if there is already a record in this table, if any, it means that he will be voting again.

That was the way.

But you also asked about "Where," so I suggest you draw borders and layers in your code. It is common knowledge that accessing the bank directly from the presentation layer is not a good practice. Ideally, you should isolate these business rules (in a separate project), so you can reuse them as needed.

It is very common to find systems divided into 3 layers. If you are new to the subject, I suggest starting with this link:

link

    
06.11.2014 / 11:47
1

Try to retrieve the vote before displaying the like / dislike link on the screen. If he has already voted, display a link showing that he has already done so. Also, let him change his vote. Again you will need to retrieve the information in the db (with the id of the user and id of the chapter) and change the value of the vote.

    
06.11.2014 / 04:25