[英]MVC route URL not containing parameter
I'm attempting to wrap my head around .NET MVC5 routing. 我正在尝试围绕.NET MVC5路由。
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
我有一个控制器Home
和一个Action ProductsCheaperThan
,它需要进行参数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
. 这会将输入中的值(假设我要发布的值为20
)发回到我的操作中,并正确地将我路由到~/Home/ProductsCheaperThan
。 The problem is, I'd like to be routed to ~/Home/ProductsCheaperThan/20
问题是,我想被路由到~/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 可能有效,并且我有一种解决方案,可以将表格更改为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. 并生成一个~/Home/ProductsCheaperThan?comparisonPrice=20
的URL,但是它使用查询字符串代替,而这与我的目的不完全相同。
Can anybody help me get my URL right? 有人可以帮助我正确设置我的网址吗?
You should add [HttpPost]
attribute to your action 您应该在操作中添加[HttpPost]
属性
[HttpPost]
public ActionResult ProductsCheaperThan(decimal comparisonPrice)
{
ViewBag.FilterPrice = comparisonPrice;
var resultSet = new ProductService().GetProductsCheaperThan(comparisonPrice);
return View(resultSet);
}
One option is to use JQuery - 一种选择是使用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
上面的脚本将导致http://localhost:1655/PriceToCompare/Home/123
我认为您可以使用重载来指定路由值:
@using (Html.BeginForm("Login", "Account", new { comparisonPrice= "20" })) { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.