title: How to stop Mvc and MvC web api function from Executing twice in slow internet connection
body: <p>I have same function in both web api and Mvc Asp.Net project that send message . In web api I use ajax call to make request which is fine on good internet connection but when the internet is slow the function will send the message twice, sometimes three times. I have also try the same with normal Mvc project and still get the same result. I don't know why my function can't send the message once. I have been trying to sort this out now for three days but don't know why it keeping sending multiple times. Any help will be so much appreciated. below is function for webapi.</p>
  
  <pre><code>[Route("Vend")]
      [HttpPost]
      public HttpResponseMessage Vend()
      {
          PayVendorModel model = new PayVendorModel();
          var rsp = new object();
          List&lt;string&gt; error = new List&lt;string&gt;();
          if (Request.Content.IsFormData())
          {
              var provider = Request.Content.ReadAsFormDataAsync();
              model = (PayVendorModel)(ModelBinders.BindModel(provider.Result, new PayVendorModel()));
  
              UserProfile userProfile = Permissions.CurrentUser();
              bool isVtuSuccess = false;
              string vtuReference = string.Empty;
  
              AirVendResponse vend = RequestManager.GetAirVendForUser(Convert.ToInt32(model.Network), model.PhoneNumber, model.Amount, userProfile.VtUUsername, userProfile.PinCode).Result;
  
  
              if (vend.VendResponse.ResponseCode == "0")
              {
                  isVtuSuccess = true;
                  vtuReference = model.PhoneNumber;
  
                  CashActivity cashAct = new CashActivity()
                  {
                      IsVtuSuccess = isVtuSuccess,
                      Network = StringUtil.CheckNetwork(Convert.ToInt32(model.Network)),
                      PhoneNumber = vend.VendResponse.Msisdn,
                      RecordState = new RecordState(new Guid(userProfile.Id)),
                      Amount = Convert.ToDecimal(vend.VendResponse.Amount),
                      AVRef = vend.VendResponse.AVRef,
                      SellRef = vend.VendResponse.Ref
  
                  };
  
                  CashProvider.Add(cashAct);
  
  
                  rsp = new
                  {
                      message = "Succeeded",
  
                  };
                  return Request.CreateResponse(HttpStatusCode.OK, rsp);
              }
              else
              {
                  rsp = new
               {
                   message = "Error Code: " + vend.VendResponse.ResponseCode + "\n Message: " + vend.VendResponse.ResponseMessage,
  
               };
                  return Request.CreateResponse(HttpStatusCode.OK, rsp);
  
              }
          }
          else
          {
  
              error.Add("Error Creating Store.");
              return Request.CreateResponse(HttpStatusCode.BadRequest, ModelHelper.GetStringError(error));
  
          }
      }
  </code></pre>
  
  <p>Ajax</p>
  
  <pre><code> $("#VendSaveBtn").unbind().bind("click", "#VendSaveBtn", function (e) {
  
      (e.preventDefault) ? e.preventDefault() : e.returnValue = false;
      if (!ValidateVend())
          CreateVend();
  
  
  });
  
  function CreateVend() {
      $.ajax({
          type: 'POST',
          timeout: GetTimeOut(),
          url: storeUrl + 'Vendor/Vend',
          data: $("#UserVendForm").serialize(),
          beforeSend: function (xhr) {
              xhr.setRequestHeader('Authorization', GetTokenHeader());
          },
          success: function (result) {
              if(result.message =="Succeeded")
                  changepage('#nav-panel');
              else
                  createPopup(result.message)
  
          },
          error: function (req, s, t) {
              hideLoading();
              if (req.status == 401) {
                  RemoveAccess();
                  changepage("#LoginPage");
              }
              if (s === "timeout") {
                  createPopup("Alert:", "Oops! check your internet connection.")
              } else if (req.status == 0) {
                  createPopup("Alert:", internetMessage)
              } else if (req.status == 408) {
                  createPopup("Alert:", internetServerError);
              } else {
                  var messageArray = req.responseText;
                  if (messageArray != undefined || messageArray != "") {
                      var newArray = JSON.parse(messageArray);
                      if (newArray.length &gt; 1) {
                          for (var i = 1; i &lt; newArray.length; i++) {
                              createPopup("Alert:", newArray[i].message);
                          }
                      } else {
                          $.each(newArray, function () {
  
                              createPopup("Alert:", this.message);
                          });
                      }
                  } else {
                      createPopup("Alert", "Oops something went wrong please try again.")
                  }
              }
          }
      });
  </code></pre>
  
  <p>From normal MVC</p>
  
  <pre><code>    @using (Html.BeginForm("PayCash","User", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
          {
              @Html.AntiForgeryToken()
              @Html.ValidationSummary(true, "", new { @class = "text-danger" })
              &lt;div class="form-group"&gt;
                  &lt;label class="col-sm-3 control-label" for="card-holder-name"&gt;Phone Number&lt;/label&gt;
                  &lt;div class="col-sm-6"&gt;
                      @*&lt;input type="text" style="height:50px" class="form-control" name="card-holder-name" id="card-holder-name" placeholder="Phone Number"&gt;*@
                      @Html.TextBoxFor(m =&gt; m.PhoneNumber, new { @class = "form-control", @style = "height:50px", @placeholder = "Phone Number", type = "number" })
                      @Html.ValidationMessageFor(m =&gt; m.PhoneNumber, null, validationStyle)
                  &lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="form-group"&gt;
                  &lt;label class="col-sm-3 control-label" for="card-holder-name"&gt;Amount&lt;/label&gt;
                  &lt;div class="col-sm-6"&gt;
                      @*&lt;input type="number" style="height:50px" class="form-control" name="card-holder-name" id="card-holder-name" placeholder="Amount"&gt;*@
                      @Html.TextBoxFor(m =&gt; m.Amount, new { @class = "form-control", @style = "height:50px", @placeholder = "Amount", type = "number" })
                      @Html.ValidationMessageFor(m =&gt; m.Amount, null, validationStyle)
                  &lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="form-group"&gt;
                  &lt;label class="col-sm-3 control-label" for="expiry-month"&gt;Network&lt;/label&gt;
                  &lt;div class="col-sm-9"&gt;
                      &lt;div class="row"&gt;
                          &lt;div class="col-xs-6"&gt;
                              @Html.DropDownListFor(model =&gt; model.Natwork, new SelectList(Model.Networks, "Value", "Text"), "Select", new { @class = "form-control col-sm-2", @style = "height:50px" })
                              @Html.ValidationMessageFor(m =&gt; m.Natwork, null, validationStyle)
                          &lt;/div&gt;
  
                      &lt;/div&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="form-group"&gt;
                  &lt;label class="col-sm-3 control-label" for="expiry-month"&gt;&lt;/label&gt;
                  &lt;div class="col-sm-offset-9"&gt;
                      &lt;div class="row"&gt;
                          &lt;div&gt;
                              &lt;input type="submit" style="height:50px;width:200px" value="Send" class="btn btn-success"&gt;
                          &lt;/div&gt;
  
                      &lt;/div&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
          }
  </code></pre>
  
  <p>MVC function</p>
  
  <pre><code>[HttpPost]
      public async Task&lt;ActionResult&gt; PayCash(PayVtuModel model)
      {
          if (ModelState.IsValid)
          {
              UserProfile userProfile = Permissions.CurrentUser();
              bool isVtuSuccess = false;
              string vtuReference = string.Empty;
  
              AirVendResponse vend= await RequestManager.GetAirVendForUser(Convert.ToInt32(model.Natwork), model.PhoneNumber, model.Amount, userProfile.VtUUsername, userProfile.PinCode);
  
              if (vend.VendResponse.ResponseCode == "0")
              {
                  isVtuSuccess = true;
                  vtuReference = model.PhoneNumber;
  
                  CashActivity cashAct = new CashActivity()
                  {
                      IsVtuSuccess = isVtuSuccess,
                      Network = StringUtil.CheckNetwork(Convert.ToInt32(model.Natwork)),
                      PhoneNumber = vend.VendResponse.Msisdn,
                      RecordState = new RecordState(new Guid(userProfile.Id)),
                      Amount = Convert.ToDecimal(vend.VendResponse.Amount),
                      AVRef = vend.VendResponse.AVRef,
                      SellRef = vend.VendResponse.Ref
  
                  };
  
                  CashProvider.Add(cashAct);
  
                  return RedirectToAction("Index", "User");
              }
              else
              {
  
                  ModelState.AddModelError("", "Error Code: " + vend.VendResponse.ResponseCode + "\n Message: " + vend.VendResponse.ResponseMessage);
              }
          }
          return View(model);
  
      }
  </code></pre>