Assaf Our Assaf Our - 1 month ago 11
Ajax Question

ajax post not posting all form values to controller

I have a from that I add it with a script Latitude & latitude ,and pass it to a textInput and then I post it to the controller with ajax, how ever the value in this "dynamic" text input is always null at the controller side and has value when I inspect the element.

<script type="text/javascript">
function GetLocation() {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("txtAddress").value;
var labelvar = document.getElementById('sys');

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.lng();
console.log("Latitude: " + latitude + "\nLongitude: " + longitude); //Ok.

labelvar.innerHTML = latitude + longitude; //Ok.

$.ajax({
url: 'Create',
type: 'POST',
data: $('#RestoForm').serialize(),
datetype: "html",
success: function(data) {
$('#RestoForm').html(data);
}
});

error: function e(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
}
});
};
</script>


[Authorize]
public ActionResult Create()
{
var viewModel = new LectureFormViewModel
{
Genres = _context.Genres.ToList(),
};
return View("TGigform", viewModel);
}

[Authorize, HttpPost, ValidateAntiForgeryToken]
public ActionResult Create(LectureFormViewModel viewModel)
{
try
{
if (!ModelState.IsValid)
{
viewModel.Genres = _context.Genres.ToList();
return View("TGigform", viewModel);
}

var lectureGig = new LectureGig
{
LatLong = viewModel.LatLong,
};


@using (Html.BeginForm("Create", "TMaps", FormMethod.Post, new {enctype = "multipart/form-data", id = "RestoForm"}))
{
@Html.LabelFor(m => m.LatLong)
@Html.TextBoxFor(m => m.LatLong, new {@id = "sys"})
<input type="button" class="btn btn-primary btn-lg" onclick="GetLocation()" value="Finish"/>
}


All other values except
labelvar
are fine and get to the controller.
thanks

Answer

Assuming that labelvar is an input element you need to set its value, not its innerHTML. Try this:

labelvar.value = latitude + longitude;