2

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?

2
  • I assume the Search route is listed before the MainIndex route in your code (just like you have it in your post), correct? Commented Nov 4, 2010 at 11:55
  • Yes, Hector. The search route is listed before the MainIndex route. Commented Nov 4, 2010 at 14:11

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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.

1 Comment

No, that wasn't the cause of the error since the route was well made. Only the route search was not caught while making the action attribute of the form, because the route demanded the query parameter which did not exist before the form was submitted ("/search" did not correspond to the route "search/{query}"). But thanks! Good try +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.