I have a html form where the user enters his address (geo location - street, city, and so on). Now i want to retrieve the latitude and longitude of that address when the user clicks submit button. My code looks like this: View:
@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>
}
Model:
public class RentOutSpace
{
[HiddenInput(DisplayValue = false)]
public string latitude { get; set; }
[HiddenInput(DisplayValue = false)]
public string longitude { get; set; }
public string address { get; set; }
}
Controller
[HttpPost]
public ActionResult AddSpace(RentOutSpace rentModel)
{
Session.Store(rentModel);
Session.SaveChanges();
return View();
}
My question is how can i pass the field value of the address to my JavaScript function and pass the latitude and longitude variables values to my model, so i can save them in a database?
This page seems to offer what you're after via jquery and $.post()
See section "Sending Form Data via AJAX"
http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.