Friday, 16 August 2013

MVC4 calling Javascript function from View

MVC4 calling Javascript function from View

The code below works if you enter a city and state, then click outside of
the text box but NOT directly on the Search submit button. Clicking
outside of the text box triggers the onblur event which fires the
javascript code to run a bing maps geocode on the city and state and
populates the two hidden text boxes with the latitude and longitude. THEN
when you click the submit button the code passes the latitude and
longitude into the CityDistanceSort action on the Job controller which
sorts the cities in the database based on their distance from the latitude
and longitude passed in, then posts that sorted model to the view.
Everything works except that you need to be able to enter the City and
State and then of course just click the Submit button directly. But doing
so doesn't give the JS code time to geocode and causes an error: The
parameters dictionary contains a null entry for parameter 'SearchLatitude'
of non-nullable type 'System.Double...
@using(Html.BeginForm("CityDistanceSort", "Job"))
{
<input type="hidden" name="SearchLatitude" id="SearchLatitude">
<input type="hidden" name="SearchLongitude" id="SearchLongitude">
<input type="text" name="CityStateName" id="CityStateName"
placeholder="CITY, BY DISTANCE" onblur="GeocodeSearchCityState()">
<input type="submit" value="SEARCH" />
}



[HttpPost]
public ActionResult CityDistanceSort(double SearchLatitude, double
SearchLongitude)
{
var model = db.Jobs.ToList();
foreach (var item in model)
{ item.PickupDistanceSort =
ICN.CustomMethods.GetDistance(SearchLatitude, SearchLongitude,
item.PickupLatitude, item.PickupLongitude); }
return View("JobHeadings", model.OrderBy(s => s.PickupDistanceSort));
}

No comments:

Post a Comment