views:

48

answers:

2

I want clean URLs and have defined two routes:

routes.MapRoute(
    "Search",
    "Search",
    new { controller = "Search", action = "SearchPanel" }
);
routes.MapRoute(
    "SearchResults",
    "Search/{content}",
    new { controller = "Search", action = "Search", content = string.Empty, query = string.Empty, index = 0 }
);

then I have two actions:

[HttpPost]
public ActionResult Search(string content, string query)
{
    if (string.IsNullOrEmpty(query))
    {
        return RedirectToAction("Home", "Application");
    }
    return RedirectToAction("Search", new { content = content, query = query }); ;
}

public ActionResult Search(string content, string query, int? index)
{
    if (string.IsNullOrEmpty(query))
    {
        return RedirectToAction("Home", "Application");
    }

    switch (content)
    {
        case "products":
            // get products
            return View("ResultsProducts");
        case "categories":
            // get categories
            return View("ResultsCategories");
        default:
            // get all
            return View("ResultsAll");
    }
}

I have a generic search panel in my master page that has a textbox and a submit button. It posts to /Search. Textbox's name is query. All fine and great. When I hit Search my first action gets executed, but fails on RedirectToAction() call:

No route in the route table matches the supplied values.

I can't seem to find the reason why it doesn't work.

+1  A: 

Removing content, query and index from defaults in second route, resolved the problem. Why is that I can't really tell, because those just define defaults, when they're not provided which in my case is not the case. I'm providing those values anyway.

Robert Koritnik
I had a similar issue after updating to release 2 of MVC. I could navigate to the page specifying the URL, but if I tried to use RedirectToAction("ActionName") I got the same error: "No route in the route table...." In my case, I ended up duplicating the route entry the was working using the URL and removed the other parameters and now the RedirectToAction works also. Very strange....But thanks for the tip.
Rick
A: 

I had the same problem, and thankfully this helped me so I want to give something back.

It seems there was a change in the MVC 2 framework which forces you to declare the routes in a different way.

In order to have the extra route values there (e.g. content) you must not assign the default of string.Empty, but rather have

content = UrlParameter.Optional

This should then allow your route evaluations to behave like it did in MVC 1.

Wiaan