1

I have a problem with a function: when I click a button, a code block is running but when the user clicks the button or link more than once, this code block is running more than once without the run being completed.

So some times it writes data to the database twice. I'm using ASP.NET MVC and C#.

Here my example code:

[Route("Reservations")]
public ActionResult Index()
{            
    MTAPI mTAPI = new MTAPI();
    mTAPI.VeriAl();

    reservations.EditPassedTourTime();
    reservation.Raccount = reservations.GetAllResAccountLMTD();           

    return View(reservation);
}

public void VeriAl()
{
    int VoucherId = rservations.GetLastVoucher().fldId;

    using (example _db= new example())
    {
        var newdata =_db.Voucher();
        newdata.beforerecordId = VoucherId;
        _db.Voucher.Add(newdata);
        _db.SaveChanges();
    }  
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    You can either disable the Submit button after the first click (using Javascript and a click handler) or you can use the [Post/Redirect/Get pattern](https://stackoverflow.com/a/4250838/2791540) – John Wu May 03 '21 at 21:12
  • I think this is not solve my problem because code block can fire by refresh the page so if user push f5 more than one i got same issue. Thank you quick response. – Semih Can Bilgen May 03 '21 at 21:53

1 Answers1

1

I found a solition for my problem. I am open for new offers.

I put a bool variable which is true until function complated.

codes;

  [Route("Reservations")]
public ActionResult Index()
{            
    MTAPI mTAPI = new MTAPI();
    mTAPI.VeriAl();
    rservations.EditPassedTourTime();
    reservation.Raccount = rservations.GetAllResAccountLMTD();           
    return View(reservation);
}
  public class dd
    {
       public bool isSearching = false;
    }
 
 public void VeriAl()
{
 bb:
   if (dd.isSearching == true) { System.Threading.Thread.Sleep(1000); goto bb; }
        dd.isSearching = true;
   int VoucherId = rservations.GetLastVoucher().fldId;
   using (example _db= new example())
   {
    var newdata =_db.Voucher();
    newdata.beforerecordId=VoucherId;
    _db.Voucher.Add(newdata);
    _db.SaveChanges();
 dd.isSearching = false;
   }  
}