开发者

Get form-values from HTTP-get?

开发者 https://www.devze.com 2022-12-13 11:44 出处:网络
I\'m using ASP.NET adn have the following code in my view: <% using(Html.BeginForm(\"Search\", \"Home\", FormMethod.Get)) { %>

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(st开发者_开发问答ring 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消