2017-02-16 52 views
0

我在MVC項目中,我有一個@Ajax.BeginForm()具有以下字段有一個奇怪的設置: -與MVC jQuery的AJAX調用順序

  • 地址行1
  • 地址行2
  • 郵編

我們需要去Google地理編碼與這個地址,並獲得點擊阿賈克斯表單上的提交按鈕的經度和緯度。所以: -

@using (Ajax.BeginForm("EditLocation", "Location", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "new-locations", OnBegin = "return OnBegin()", OnSuccess = "OnSuccess()", InsertionMode = InsertionMode.InsertBefore }, new { @id = "EditLocationForm" })) { 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(false) 
    <!-- Standard Text Fields --> 
    @Html.TextBoxFor(m => m.Latitude) 
    @Html.TextBoxFor(m => m.Longitude) 
    <input type="submit" class="btn btn--gradient btn--right" id="EditLocationSubmit" /> 
} 

function OnBegin() { 
    $.ajax({ 
     url: '/Location/CheckAddress/', 
     datatype: "json", 
     async: false, 
     data: { addressLine1: $("#BrandLocationAddress_AddressLine1").val(), addressLine2: $("#BrandLocationAddress_AddressLine2").val(), town: $("#BrandLocationAddress_Town").val(), county: $("#BrandLocationAddress_County").val(), postcode: $("#BrandLocationAddress_Postcode").val(), }, 
     type: "POST", 
     success: function (data) { 
      if (data !== "NORESULTS") { 
       $("#Latitude").val(data.Latitude); 
       $("#Longitude").val(data.Longitude); 
       return true; 
      } 
      else { 

      } 
     }, 
     error: function (response) { 
      console.log(response); 
      return false; 
     } 
    }); 
} 

的/地區的結果/ CheckAddress /帶回緯度和經度預期,但Ajax.BeginForm()進入表單提交被填充兩個#Latitude和#Longitude領域之前。當我查看模型的[HttpPost]時,經度和緯度爲0.

當我第二次發佈時,這些字段是正確的緯度和經度值。我想這可能是因爲OnBegin()被允許Ajax.BeginFormsuccess條款的最後一行之前做的東西已經被執行,因此0

任何人都可以提供建議的方式,使第二形式提交延遲,直到我知道success條款的最後一行已經完成?

+1

刪除'async:false'。這是令人難以置信的糟糕做法,因爲它鎖定了瀏覽器的UI線程。如果你檢查控制檯,瀏覽器甚至會給你警告,不要使用同步請求 –

+0

擺脫'Ajax.BeginForm()'並使用'$ .ajax()'(你已經在使用它了,那麼爲什麼你需要Ajax .BeginForm())。處理'.submit()'事件,讓你ajax調用獲取座標,並在其成功回調中,讓你調用'EditLocation()'ajax' –

回答

1

你需要從你的函數返回false

var allowSubmit = false; 
function OnBegin() { 
    if (allowSubmit == true) { return true; } 
    $.ajax({ 
     // ... code 
     success: function (data) { 
      // ... code 
      // here you need to submit the form using 
      $("#EditLocationForm").submit() 
      allowSubmit = true; 
     }, 
     error: function (response) { 
      // .. code 
     } 
    }); 

    return false; 
} 

success,提交表單,如圖碼以上。

另外,不要使用async: false來做到這一點:在操作正在進行時,您不想凍結UI。您可能想要做的是禁用控件,以便用戶無法更改它們,然後在successerror中重新啓用它們。

+0

嗨,我已經試過了,但它進入了一個連續的循環一次又一次地調用初始的AJAX調用。有什麼建議嗎?我之前已經安裝了這個設置,但在發生這種情況後放棄了它 –

+1

@MikeUpjohn對不起邁克,請看我的編輯。 – CodingYoshi