I have the following actions in my home controller. when i post to the GetDistance() it never goes to the /Home/ShowDistance page but stays on the /Home/Index page. I have checked that the lat and lon values are not null so the browser should be redirected to /Home/ShowDistance.
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult GetDistance(string lat, string lon)
{
if (lat != null && lon != null)
{
Session["latlon"] = new LatLon { Latitude = double.Parse(lat), Longitude = double.Parse(lon) };
return RedirectToAction("ShowDistance");
}
return RedirectToAction("Index");
}
public ActionResult ShowDistance()
{
//...
return View();
}
In your
Index.cshtmlview make sure that you specify the correct controller action to post to (because it has a different name than the one used to render the form). So instead of:use:
Or if you don’t use a standard HTML
<form>to invoke theGetDistanceaction but an AJAX call, then it’s perfectly normal that the browser url stays at/Home/Index. The whole point of AJAX is to perform an asynchronous HTTP request to the server without navigating away from the current page (which in your case is/Home/Index). If this is the case and you want to redirect you will have to do it on the client in the success callback:You will also have to modify your
GetDistancePOST action so that instead of redirecting it returns a JSON object containing the target url to redirect to that can be used in the success callback:Obviously this kind of defeats the purpose of AJAX a little because as I said the whole point of AJAX is to perform asynchronous requests to the server and stay on the same page. So in this case you should probably stick with a standard HTML
<form>.