views:

154

answers:

1

I'm using ASP.NET adn have the following code in my view:

<% using(Html.BeginForm("Search", "Home", FormMethod.Get)) { %>

<%= Html.TextBox("searchText") %>
<input type="submit" value="Search" />

<% } %>

and in my controller I have:

    public ActionResult Search(string searchText)
    {
       return View("Index");
    }

If I have a breakpoint in the Search-action and examine the searchText argument it's always "" even if I type some text in the texbox. If I change the formmethod to POST it works as expected.

How can I read "searchText" when using http-GET?

Edit:

I had the following route

       routes.MapRoute(
            "Search",                                              // Route name
            "Search/{searchText}",                           // URL with parameters
            new { controller = "Home", action = "Search", searchText ="" }  // Parameter defaults
        );

and when I removed the default value of searchText(searchValue=""), then I got the correct value in my action. Why?

+1  A: 

Use Firebug or Fiddler to look at the actual URI. You have a "searchText" part of your route, and I'm betting you have a "searchText" query string parameter, too.

To make searchText part of the path portion of the URI, you would need to use JavaScript to rewrite the URI for the form, because HTML forms don't know about your MVC routing. On the other hand, HTML forms do query string parameters "out of the box", and MVC will bind them to action arguments without even including them in the route.

The easiest solution is to remove searchText from your route altogether and just use the query string parameter. You don't need to do anything but change the route to make this work.

Craig Stuntz