Fabio Milheiro
Fabio Milheiro

Reputation: 8474

ASP.Net MVC Routes not working properly

We have several routes in our Global.asax.cs file, but one of them is not apparently being used.

// Search (NOT working).
routes.MapRoute(
         "Search",
         "search/{query}",
         new { controller = "Search", action = "Index" });

// Homepage (I believe the problem could be here, but not sure).
routes.MapRoute(
         "MainIndex",
         "{language}",
         new { controller = "Main", action = "Index", language = string.Empty });

When we do a search in the search form which action attribute is "/Search", the user is sent to the homepage and the URL in the address bar is "/Search?query=example+search".

The form action attribute is built in using this code:

<form id="form1" action="<%= Url.Action("Index", "Search") %>">

Seems right to me, but the action name should be "/search" instead of "/Search", right?

Upvotes: 2

Views: 1117

Answers (3)

dotariel
dotariel

Reputation: 1594

I always find this tool extremely helpful in debugging routes. Route Debugger

Upvotes: 2

Hector Correa
Hector Correa

Reputation: 26680

I just tried your route with the following view

<form id="form1"  method="post" action="<%= Url.Action("Index", "Search") %>">
Enter something: <input type="text" name="query" id="query" value="hello" />
<input type="submit" />
</form>

and a controller like this

public ActionResult Index(string query)
{
    return View();
} 

and it works OK. Notice that (1) I am using method=post and (2) that the textbox has both a name and ID set to "query" which is what the Html.TextBox would have done for you. This is what allowed the binding to pick up the value and pass it correctly to the controller.

Upvotes: 3

amurra
amurra

Reputation: 15401

Try making the "search/{query}" match the case => "Search/{query}"

Well your action on the form tag is /Search/Index, which will match your Search/{query} route, but your query will be Index. However, with the ?query=example+search on the end of your route, the Search route won't know how to handle that query parameter. I would just update the action attribute on the form tag to just be /Search and not use the URL helper.

Upvotes: 1

Related Questions