我正在尝试理解.NET MVC5路由。
我有一张表格:
@using (Html.BeginForm("ProductsCheaperThan", "Home", FormMethod.Post))
{
<input type="text" name="comparisonPrice" />
<button type="submit">Search!</button>
}我有一个控制器Home和一个带有参数comparisonPrice的动作ProductsCheaperThan
public ActionResult ProductsCheaperThan(decimal comparisonPrice)
{
ViewBag.FilterPrice = comparisonPrice;
var resultSet = new ProductService().GetProductsCheaperThan(comparisonPrice);
return View(resultSet);
}这会将输入中的值发送回我的操作(假设我发送的值是20),并正确地将我路由到~/Home/ProductsCheaperThan。问题是,我希望被路由到~/Home/ProductsCheaperThan/20
我喜欢这样做,这样如果有人给页面加了书签,他们在重新访问页面时就不会收到错误。
我认为添加如下内容:
routes.MapRoute(
name: "ProductsCheaperThan",
url: "Home/ProductsCheaperThan/{comparisonPrice}",
defaults: new { controller = "Home", action = "ProductsCheaperThan", comparisonPrice = 20 }
);可能行得通,我对我的问题有一个解决方案,那就是将表单更改为GET
@using (Html.BeginForm("ProductsCheaperThan", "Home", FormMethod.Get))并生成一个~/Home/ProductsCheaperThan?comparisonPrice=20的网址,但它使用的是查询字符串,这并不是我的目标。
有没有人能帮我把URL弄对?
发布于 2015-06-07 21:30:24
您应该将[HttpPost]属性添加到操作中
[HttpPost]
public ActionResult ProductsCheaperThan(decimal comparisonPrice)
{
ViewBag.FilterPrice = comparisonPrice;
var resultSet = new ProductService().GetProductsCheaperThan(comparisonPrice);
return View(resultSet);
}https://stackoverflow.com/questions/30694066
复制相似问题