mvc2 - getting the URL to reflect the form submission
I have an MVC2 application with a form (like ya do). The user enters a query into the form (in the /Cars/Index view) and hits the "submit" button which posts to the Details action of CarsController - the Details view renders with results, and all is well and good.
The user can enter a URL (such as /Cars/Details/123-125) and they get the Details view with 123, 124 and 125 displayed, same as if you'd entered it on the form. Also well and good.
What I want to enable, if possible, is that when the user enters "123-125" or whatever in the form the URL also reflects the results - instead of "/Cars/Details" for a URL, which is what shows now, I want it to show "/Cars/Details/123-125".
For the life of me, I cannot figure out how this should be done开发者_StackOverflow.
Any assistance is appreciated.
Change your form to a GET
instead of POST
method (POST is the default), and it should just work.
<% using (Html.BeginForm("Action", "Controller", FormMethod.Get)) { %>
It sounds like its not finding a matching route definition for /Cars/Details/123-125. I think this could be happening because of the way the routing engine works.
ASP.NET MVC Route Contraints with {ID}-{Slug} Format
Ok, here is the answer I came up with:
In short: Redirect to GET
Basically, I write an action with [HttpPost] Attribute that redirects the form submittal to another action with [HttpGet] attribute. The route works whether you submit the form or type in the URL manually.
[HttpPost]
public ActionResult Details(CarViewModel model, int? pageNbr) {
// simply takes the form POST and re-routes it as a GET to pretty up the URL
// (see second Details action)
int page = pageNbr ?? 0;
return RedirectToAction("Details", new { query = model.Query, pageNbr = page });
}
[HttpGet]
public ActionResult Details(CarViewModel model, int pageNbr)
{
// various magic to create the view...
return View(avm);
}
As an added bonus, this takes care of the "Are you sure you want to resubmit?" annoyance when someone refreshes the page or hits the BACK button in their browser.
精彩评论