Prevent the user from voting in the same Post

Asked

Viewed 52 times

0

I created a voting system, where users can give like/dislike in the chapters of books posted on the site. Follow 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 I could do this check?

2 answers

3

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

That was how.

But you also asked about "Where," so I suggest you draw borders and layers in your code. It is common knowledge that accessing the direct database of the presentation layer is not a good practice. Ideally, you can isolate these business rules (in a separate project), so you can reuse them when 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:

http://pt.wikipedia.org/wiki/Modelo_em_tr%C3%AAs_camadas

1

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

Browser other questions tagged

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