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

2019-09-10 08:30发布

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.

4条回答
Evening l夕情丶
2楼-- · 2019-09-10 09:05

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

查看更多
我只想做你的唯一
3楼-- · 2019-09-10 09:07

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?

查看更多
Bombasti
4楼-- · 2019-09-10 09:10

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" />
    }
}
查看更多
Melony?
5楼-- · 2019-09-10 09:17

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

查看更多
登录 后发表回答