【发布时间】:2017-02-16 15:34:50
【问题描述】:
我在一个 MVC 项目中有一个奇怪的设置,我有一个 @Ajax.BeginForm(),其中包含以下字段:-
- 地址线1
- 地址线2
- 城镇
- 县
- 邮政编码
我们需要用这个地址去谷歌地理编码,并通过点击 Ajax 表单上的提交按钮来获取纬度和经度。所以:-
@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;
}
});
}
/Location/CheckAddress/ 的结果按预期返回纬度和经度,但 Ajax.BeginForm() 在填充两个 #Latitude 和 #Longitude 字段之前进入表单提交。当我查看模型的[HttpPost]时,纬度和经度都是0。
当我第二次发布时,这些字段是正确的纬度和经度值。我认为这可能是因为OnBegin() 允许Ajax.BeginForm 在success 子句的最后一行执行之前完成它的工作,因此为0。
谁能建议在我知道success 子句的最后一行完成之前延迟提交第二个表单的方法?
【问题讨论】:
-
删除
async: false。这是非常糟糕的做法,因为它锁定了浏览器的 UI 线程。如果您检查控制台,浏览器甚至会警告您不要使用同步请求 -
摆脱
Ajax.BeginForm(),只使用$.ajax()(你已经在使用它了,为什么还要Ajax.BeginForm())。处理.submit()事件,让你ajax调用来获取坐标,并在它的成功回调中,让你ajax调用EditLocation()
标签: c# jquery ajax asp.net-mvc ajax.beginform