-2

I have a page of announcements that when a user views it, adds it to a "seen" database. The issue with this is, if I user then clicks the same page twice then it records that twice and so on. Here is my code, How could I check if the entry already exists in the database?

public ActionResult Index()
{
    string currentUserId = User.Identity.GetUserId();
    var currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);

    List<Seen> seens = new List<Seen>();  

    foreach (Announcement anoun in db.Announcements)
    {
        seens.Add(new Seen
                      {
                          User = currentUser, // You have this already so why go to the database again?
                          Announcement = anoun, // Same with this.
                      });
    }

    db.Seens.AddRange(seens);
    db.SaveChanges();

    return View(db.Announcements.ToList());
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user3042332
  • 81
  • 1
  • 7

3 Answers3

1

There are several things to consider:

1) database integrity - consider adding UNIQUE constraints as a safety net for business uniqueness - in your case (SeenId, UserId) or something similar. This will also add an index that makes some selections faster.

2) prevent double submit - first point prevents persistence of duplicates, but will also lead to error. In order to avoid this, you should take a look upon preventing double submission.

In MVC, a question dealing with preventing double submission shows how Post/Redirect/Get Pattern is implemented in MVC.

Community
  • 1
  • 1
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
0

How could I check if the entry already exists in the database?

well , you could simply set your SQL field to Unique to prevent multi entry of data , As I assume that you are working on a social network type of app and you want each user to be able to "view" your post/page only once.

another way is to use the same loop to search for the value in the field , and if it is there then it it just quits the process.

Sina M.Azad
  • 27
  • 1
  • 9
0

There is some ways you can prevent it.

  • Set your value as primary key in your database/table (uniqueness)

  • Check for existing value in your code behind before inserting into DB (redirect or return message if exist)

  • Disable submission button in client side page just after first click

Shaahin
  • 1,195
  • 3
  • 14
  • 22