Reputation: 411
I'm attempting to wrap my head around .NET MVC5 routing.
I've got a form:
@using (Html.BeginForm("ProductsCheaperThan", "Home", FormMethod.Post))
{
<input type="text" name="comparisonPrice" />
<button type="submit">Search!</button>
}
And I've got a controller Home
and an action ProductsCheaperThan
which takes a parameter comparisonPrice
public ActionResult ProductsCheaperThan(decimal comparisonPrice)
{
ViewBag.FilterPrice = comparisonPrice;
var resultSet = new ProductService().GetProductsCheaperThan(comparisonPrice);
return View(resultSet);
}
This posts the value in the input (let's suppose that the value I'm posting is 20
) back to my action, and correctly routes me to ~/Home/ProductsCheaperThan
. The problem is, I'd like to be routed to ~/Home/ProductsCheaperThan/20
I'd like to do this so that if somebody bookmarks the page they don't end up getting an error when they revisit the page.
I thought that adding something like:
routes.MapRoute(
name: "ProductsCheaperThan",
url: "Home/ProductsCheaperThan/{comparisonPrice}",
defaults: new { controller = "Home", action = "ProductsCheaperThan", comparisonPrice = 20 }
);
might work, and I have one solution to my problem which changes the form to a GET
@using (Html.BeginForm("ProductsCheaperThan", "Home", FormMethod.Get))
and produces a URL of ~/Home/ProductsCheaperThan?comparisonPrice=20
, but that uses a query string instead, and isn't exactly what I was aiming for.
Can anybody help me get my URL right?
Upvotes: 0
Views: 825
Reputation: 17182
One option is to use JQuery -
<div>
<input type="text" name="comparisonPrice" id="comparisonPrice" />
<button type="button" id="Search">Search!</button>
</div>
@section scripts{
<script>
$(function () {
$("#Search").click(function () {
window.location = "@Url.Action("PriceToCompare", "Home")" + "/" + $("#comparisonPrice").val();
});
});
</script>
}
Above script will result in - http://localhost:1655/PriceToCompare/Home/123
Upvotes: 1
Reputation: 63
I think you can specify your route values using an overload:
@using (Html.BeginForm("Login", "Account", new { comparisonPrice= "20" }))
{
...
}
Upvotes: 0
Reputation: 471
You should add [HttpPost]
attribute to your action
[HttpPost]
public ActionResult ProductsCheaperThan(decimal comparisonPrice)
{
ViewBag.FilterPrice = comparisonPrice;
var resultSet = new ProductService().GetProductsCheaperThan(comparisonPrice);
return View(resultSet);
}
Upvotes: 1