views:

38

answers:

1

Despite the plethora of URL routing posts, I have yet to reach enlightenment on the subject.

I have an MVC app that works fine, but I want to get fancy and do some URL rewriting to make it easier on my users.

The default route is a slight variation on the usual:

routes.MapRoute(
      "Default",
      "{controller}/{action}/{query}",
      new{ controller = "SomeController", action="Index", query = "" });

What I want to do is re-route the URL http://mysite.com/12345 to the Details action of SomeController with the 12345 query. I tried this:

routes.MapRoute(
      "DirectToDetails",
      "{query}",
      new{ controller = "SomeController", action="Details" query="" });

routes.MapRoute(
      "Default",
      "{controller}/{action}/{query}",
      new{ controller = "SomeController", action="Index", query = "" });

but that ends up obscuring http://mysite.com/ and it goes to SomeController/Details instead of SomeController/Index.

EDIT:

per the advice of @Jon I removed the query = "" in the anonymous object:

routes.MapRoute(
      "DirectToDetails",
      "{query}",
      new{ controller = "SomeController", action="Details" });

... which addressed the question as far as it went; now when I submit the form at Views/SomeView/Index (that submits to the aforementioned SomeController/Details) I get a "resource cannot be found" error.

Here is the form declaration:

<% using (Html.BeginForm(
              "Details", 
              "SomeController", 
              FormMethod.Post, 
              new { id = "SearchForm" })) { %>
    <% Html.RenderPartial("SearchForm", Model); %>
    <%= Html.ValidationMessageFor(model => model.Query) %>
<% } %>
A: 

Remove the query = "" (obviously it's not optional exactly because of the problem you're having - no need to put it in the 3rd argument if there's no sensible default) and use the overload of MapRoute that takes a 4th parameter with route constraints:

routes.MapRoute(
  "DirectToDetails",
  "{query}",
  new { controller = "SomeController", action="Details" },
  new { query = @"\d+" });

Obviously you will need to adjust the regex if it's not an integer...


In response to your edit...make sure that you've removed the default for query from the "short" route - you've posted the default one there. Also suggest you double check the form and make sure it's posting a value for query (maybe set a break point on the post action method and make sure the query parameter is being bound correctly?).

Jon
That works to the extent I requested - thank you. However, now when I submit the form ("doing it the hard way") I get a resource cannot be found error. I will edit the question to reflect this.
ScottSEA
ScottSEA