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.
I think you want to take a look at the @Html.BeginRouteForm method, like in this question.
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:
- The IIS url rewrite - http://www.iis.net/downloads/microsoft/url-rewrite
- Url rewrite through a web.config - http://www.hanselman.com/blog/RedirectingASPNETLegacyURLsToExtensionlessWithTheIISRewriteModule.aspx
And a batch of stupid methods:
- You can change your request to
POST
and then modificate the Url by the JS - Modify the URL without reloading the page
- You can redirect the request
Also, did you try to add a personal routing for the search url?
Try using a model for the form submit and use @Html.TextBoxFor.
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" />
}
}