How to change the way the Url is formatted on a su

2019-09-10 08:52发布

问题:

I have a search box in a Razor template:

    @{
        using (Html.BeginForm("Detail", "Book", FormMethod.Get))
        {
        @Html.TextBox("Id")
        <input type="submit" value="Search" />
        }
    }

When I submit a search it goes to a url like:

~/Book/Detail?Id=1234

However I want it to format the url like so, just because I think it looks cleaner:

~/Book/Detail/1234

Which works perfectly fine because the controller method signature looks like this:

    // GET: /Book/Detail/id
    public ActionResult Detail(string id)

Model with TextBoxFor

I've tried a Html.TextBoxFor:

    @model WebApplication.Models.SearchModel
    @{
        using (Html.BeginForm("Detail", "Book", FormMethod.Get))
        {
        @Html.TextBoxFor(m => m.Id)
        <input type="submit" value="Search" />
        }
    }

Same result.

回答1:

I think you want to take a look at the @Html.BeginRouteForm method, like in this question.



回答2:

You use a GET request. This means that all parameters will appear in the url box. I can't check now, but I suppose you could use these options:

  1. The IIS url rewrite - http://www.iis.net/downloads/microsoft/url-rewrite
  2. Url rewrite through a web.config - http://www.hanselman.com/blog/RedirectingASPNETLegacyURLsToExtensionlessWithTheIISRewriteModule.aspx

And a batch of stupid methods:

  1. You can change your request to POST and then modificate the Url by the JS - Modify the URL without reloading the page
  2. You can redirect the request

Also, did you try to add a personal routing for the search url?



回答3:

Try using a model for the form submit and use @Html.TextBoxFor.



回答4:

The answer was to add a new search action then redirect to the detail. This is nice because I can choose to do more when searching, such as returning a different view if the query has multiple matches.

    //
    // GET: /Book/Search?query=
    public ActionResult Search(string query)
    {
        return RedirectToAction("Detail", new { id = query });
    }

    //
    // GET: /Book/Detail/id
    public ActionResult Detail(string id)

Razor:

@{
    using (Html.BeginForm("Search", "Book", FormMethod.Get))
    {
        @Html.TextBox("query")
        <input type="submit" value="Search" />
    }
}