0

I'm trying to build a website that enables users to vote for things. The website works, but a user can vote multiple times. How can I prevent that?

I read online that I can use cookies. But I don't know how to implement them in my ASP.NET MVC 5 project.

Can you tell me how to use cookies for preventing multiple voting in ASP.NET MVC 5?

A small code snippet for starting would be great.

stuartd
  • 70,509
  • 14
  • 132
  • 163
jason
  • 6,962
  • 36
  • 117
  • 198

1 Answers1

2

<script>

    if (Cookies.get("HasAnswered") == 1) {
        $("#spn_Answered").text("Answered");
    }


    $("#btn_Answer").click(function (e) {
        e.preventDefault();
        if (Cookies.get("HasAnswered") == 1)
            alert("You have already answered the question");
        else {
            Cookies.set("HasAnswered", 1);
            $("#spn_Answered").text("Answered");
            alert("Congrats you have answered");
        }
    });

</script>
<html>
<head>
    <title>JS Cookie</title>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.1.0/js.cookie.js"></script>
</head>
<body>
    <input type="button" name="" value="Answer Now" id="btn_Answer" />
    <span id="spn_Answered"></span>
</body>
</html>

1. You can use some sort of logic and place that in a cookie. Like

If user answered then mark the cookie value to 1 else make it 0.

Ex. Cookies.set('IsReplied', 1);

2. You can use this nice JS library. https://github.com/js-cookie/js-cookie

It provides a good documentation through which you can apply the cookies easily.

Hope this helps.

Abhishek
  • 170
  • 8
  • It would be great if you could write an example. Thanks. – jason Apr 13 '16 at 11:03
  • It is not working in stack overflow envoirement. There may be somthing missing. But the code is correct. copy and paste the code on your machine and it should work. – Abhishek Apr 13 '16 at 11:59