Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC search route

I setup a search route:

routes.MapRoute(
 "Search",
 "Search/{q}",
 new { controller = "Search", action = "Index" }
);

The search form has an input box and a button. I want the search with a GET as below.

<% using(Html.BeginForm("Index", "Search", FormMethod.Get))
{%>
    <%:Html.TextBox("q")%>
        <span class="query-button">
        <input type="submit" value="select" /></span>
    <% } %>
 </div>

The action on the SearchController is:

public ActionResult Index(string q)
{
   // search logic here

   return View(new SearchResult(q));
}

The URL becomes like this: http://localhost:19502/search?q=mvc+is+great

But I want the search to be like: http://localhost:19502/search/mvc+is+great

How do I setup the route or the Html.BeginForm

like image 673
harropriiz Avatar asked May 03 '10 14:05

harropriiz


People also ask

How can use routing in ASP.NET MVC?

Routing in ASP.NET MVC cs file in App_Start Folder, You can define Routes in that file, By default route is: Home controller - Index Method. routes. MapRoute has attributes like name, url and defaults like controller name, action and id (optional).

How can search by name in MVC?

Right click on controller Folder and select template Empty MVC controller. Right click on Index method and select Strong -typed view as shown in the following figure. In above code I have two html radiobutton and one html text box and simple submit Button. Press F5 and run you application.

Where you configure route in MVC?

Configure a Route Every MVC application must configure (register) at least one route configured by the MVC framework by default. You can register a route in RouteConfig class, which is in RouteConfig. cs under App_Start folder.


1 Answers

There isn't a straightforward way to do it with just a form. A form's intended function is to transmit name/value pairs - using MVC doesn't change that.

So your options are:

  • Override the functionality of the form using Javascript by handling the submit event of the form, redirecting to the desired URL and returning false to prevent the form from actually submitting
  • Don't use a form and handle the click event of a button to do the redirect.

Your route is already correctly set up to handle this.

like image 96
Daniel Schaffer Avatar answered Sep 28 '22 05:09

Daniel Schaffer