我有一个html表单,用户输入他的地址(地理位置 - 街道,城市等)。现在,我想在用户单击“提交”按钮时检索该地址的纬度和经度。我的代码看起来像这样: 视图:
@using (Html.BeginForm(new { onsubmit = "return getCoordinates();" }))
{
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function getCoordinates() {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('@Html.Id("address")').value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat;
var longitude = results[0].geometry.location.long;
alert(latitude);
document.getElementById('@Html.Id("latitude")').value = latitude;
document.getElementById('@Html.Id("longitude")').value = longitude;
}
});
}
</script>
@Html.ValidationSummary(true, "Please correct the errors and try again")
@Html.EditorFor(model => model.latitude)
@Html.EditorFor(model => model.longitude)
<div class="editor-label">
@Html.LabelFor(model => model.address)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.address)
@Html.ValidationMessageFor(model => model.address)
</div>
}
型号:
public class RentOutSpace
{
[HiddenInput(DisplayValue = false)]
public string latitude { get; set; }
[HiddenInput(DisplayValue = false)]
public string longitude { get; set; }
public string address { get; set; }
}
控制器
[HttpPost]
public ActionResult AddSpace(RentOutSpace rentModel)
{
Session.Store(rentModel);
Session.SaveChanges();
return View();
}
我的问题是如何将地址的字段值传递给我的JavaScript函数并将纬度和经度变量值传递给我的模型,以便将它们保存在数据库中?
答案 0 :(得分:0)
此页面似乎通过jquery和$ .post()
提供您所追求的内容请参阅“通过AJAX发送表单数据”部分
http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1