Sending web form or how to keep unique records in the DB

Lets say we have a case when a user send a web form multiple times by clicking multiple times on the submit button. How can we prevent creating duplicate entries?

The one solution is using JS (Answers). After a submit of the form we prevent it submitting second time. Here is the solution in Javascript:

$("form#form1").one("submit", submitFormFunction);

function submitFormFunction(event) {
event.preventDefault();
$("form#form1").submit();
}

$("form Button").attr("disabled","1");

Second solution is to disable the send button after submit.

Third option is to send data always through ajax.
Fourth option is to show a dialog while the form data is submitted.

    The Fifth and best solution is to handle the case at the DB level. We can make our database to store only unique records.

    We can add Constraints. The constraint is with type Unique, which means the the current column will contain only unique values.

    alter table Votes add constraint UniqueUserVote unique (SurveyId, CompetitorId, PresentationId, Question_Id, User_Id)
    alter table Users add constraint UniqueUserEmail unique (Email)

    This will make the DB to throw an Exception when it tries to enter duplicate record.

    In ASP.NET MVC + EntityFramework there is no attribute the tell that a field is unique. So you have to add it manually:

    public class SQLContext : DbContext
    {
    public DbSet<user> Users { get; set; }

    public SQLContext(string connectionName)
    : base(connectionName)
    {
    Database.SetInitializer(new Initializer());

    }

    public class Initializer : IDatabaseInitializer<SQLContext>
    {
    public void InitializeDatabase(SQLContext context)
    {
    if (context.Database.Exists() && !context.Database.CompatibleWithModel(false))
    context.Database.Delete();

    if (!context.Database.Exists())
    {
    new MigrateDatabaseToLatestVersion<SQLContext, Configuration>().InitializeDatabase(context);
    context.Database.ExecuteSqlCommand("alter table Users add constraint UniqueUserEmail unique (Email)");
    context.Database.ExecuteSqlCommand(
    "alter table Votes add constraint UniqueUserVote unique (SurveyId, CompetitorId, PresentationId, Question_Id, User_Id)");
    }
    }
    }
    }

    You may also like...