I have an application that shows locations on a map. I have created a route so that I can have nice hackable URLs, like http://www.mydomain.com/paris. This works fine just typing in the URL, but I have a search form on the home page that sends a GET request. When the form is submitted, the URL displayed in the location bar is in the format http://www.mydomain.com/Dashboard?location=paris. Normally this wouldn’t matter too much as it’s hitting the correct action, but I have a backbone.js application running the show and it’s particular about the URL structure.
It may be impossible to do what I need without javascript or a redirect, because the location isn’t known when the form ACTION attribute is populated – but can anyone confirm?
Here are my routes.
public static void RegisterRoutes( RouteCollection routes )
{
routes.IgnoreRoute( "{resource}.axd/{*pathInfo}" );
routes.MapRoute(
String.Empty,
"{location}",
new {
controller = "Dashboard",
action = "Index",
id = ""
}
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
} // Parameter defaults
);
}
Here is the controller.
public class DashboardController : Controller
{
[HttpGet]
public ViewResult Index(string location)
{
return View(new AccItemSearch { Location = location });
}
}
Here is the form.
@using (Html.BeginForm("Index", "Dashboard", FormMethod.Get)) {
<h2>Where are you going?</h2>
<input type="text" placeholder="Area, town or postcode" id="location" name="location"/>
<button>Search!</button>
</div>
}
To clarify: the problem I want help with is how to have the user submit the form then land on a page with the URL: http://www.mydomain.com/searchterm and thus match the route, rather than on a page that with the URL http://www.mydomain.com/Dashboard
You will not be able to change the
actionattribute of the form during HTML generation (i.e. server side) as you simply don’t know what it should point to. So if you need the URL to end up being the exact search term the easiest bet is probably to change theactionattribute to it with JavaScript before the form is submitted, and have a controller that catches all urls that follow the http://www.domain.com/searchterm pattern.You can’t really redirect to a specific action because then that would become the URL returned to the browser, and I doubt you want one action per search term.
HTML:
jQuery:
Route:
Note that this has to be put before the default route(s).
Action:
Now if a visitor enters the term “Alaska” and submits the search form, they will end up on domain.com/Alaska.