javascript - MVC 在 jQuery 中更新 HiddenFor 并提交到 Controller

标签 javascript jquery asp.net-mvc

我正在构建一个汽车共享网站,并有一个用于浏览现有旅程的页面。页面顶部是一个搜索栏,用于搜索位置。我想使用 Google Maps API 验证地名,然后将其与坐标一起发送到 Controller ,然后在半径内进行搜索。

对于我来说,无论我使用什么代码组合,在表单提交到 Controller 之前我似乎都无法更新 HiddenFor 或搜索字段。我知道用于验证地点的代码可以正常工作,因为我在另一个页面上使用它来创建旅程。

所以理论是用户在搜索字符串文本框中输入地名,单击提交按钮,然后运行 ​​jquery 代码,验证该地点,使用地理编码器获取正确的位置,然后更新搜索字符串和坐标隐藏字段,最后发布到 Controller 。

这是我当前的代码:

@using (Html.BeginForm("BrowseJourney", "Journey", FormMethod.Post, new { id = "searchForm" }))
{    <div class="form-group" style="padding-bottom: 50px;">
        <div class="col-md-2">
            Find by location:
        </div>
        <div class="col-md-3">
            @Html.TextBox("SearchString", null, new { @class = "form-control" , id = "SearchString"})
        </div>
        <div class="col-md-2">
            Distance:
        </div>
        <div class="col-md-1">
            @Html.DropDownList("Distance", null, new { @class = "form-control" })
        </div>
        @Html.HiddenFor(model => model.SearchLatitude, new { id = "SearchLatitude" })
        @Html.HiddenFor(model => model.SearchLongitude, new { id = "SearchLongitude" })
        <div class="col-md-2">
            <input type="submit" value="Search" class="btn btn-default" id="submitButton" />
        </div>
    </div>   

}

还有 JavaScript:

   <script src="https://maps.googleapis.com/maps/api/js?v=3&key=AIzaSyD4lap4yr45W9ztvRtfNw7JA-d03UVYtx0&region=GB" type="text/javascript"></script>
    <section class="scripts">
      <script type="text/javascript">

        $('#submitButton').click(function() {
          var address = document.getElementById("SearchString").value;
          var geocoder = new google.maps.Geocoder();
          geocoder.geocode({
            'address': address,
            componentRestrictions: {
              country: 'UK'
            }
          }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
              document.getElementById("SearchString").value = results[0].formatted_address;
              document.getElementById("SearchLatitude").value = results[0].geometry.location.lat();
              document.getElementById("SearchLongitude").value = results[0].geometry.location.lng();
            } else {
              alert("Unable to find location");
              document.getElementById("SearchString").value = null;
            }
          });
        });
      </script>
    </section>

最后是 Controller :

public ActionResult BrowseJourney(string searchString, int distance, string searchLatitude, string searchLongitude)
{
}

非常感谢任何帮助!

最佳答案

它不起作用的原因是您在点击处理程序中添加代码,然后调用异步事件并等待响应。

与此同时,表单已提交。

您需要停止表单提交,并在恢复值后通过代码提交。

类似于:

bool proceed = false;
$('#searchForm').submit(function(e) {
  if (!proceed) {
    var address = $("#SearchString").val();
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      'address': address,
      componentRestrictions: {
        country: 'UK'
      }
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        $("#SearchString").val(results[0].formatted_address);
        $("#SearchLatitude").val(results[0].geometry.location.lat());
        $("#SearchLongitude").val(results[0].geometry.location.lng());
        proceed = true;  // Allow submit to proceed next time
        $('#searchForm').submit();
      } else {
        alert("Unable to find location");
        $("#SearchString").value = null;
      }
    });
  }
  return proceed;
});

注意:所有选择器请使用 jQuery。更短且更容易理解(对于 jQuery 编码人员)。 “一分钱一分货……”

关于javascript - MVC 在 jQuery 中更新 HiddenFor 并提交到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34636575/

相关文章:

javascript - 如何获取 Sencha Touch 中的关联商店?

javascript - MEAN.JS——请求对象、Express Controller 和 Mongoose 模式

javascript - Bootstrap addClass 在表单中不起作用

javascript - 使用 Node.js 从远程文件系统检索文件列表

javascript - 如何在不使用@angular/router 的情况下添加查询参数

javascript - PICARD_BRIDGE_CALLBACK 变量 JavaScript 错误

javascript - console.log 中的变量更新但不在另一个函数中

javascript - 更新 Div 添加文本、评论功能

c# - Controller 无效时出现 StructureMap 错误

asp.net-mvc - ASP.Net MVC View 结构