【问题标题】:MVC route URL not containing parameterMVC 路由 URL 不包含参数
【发布时间】:2015-06-07 13:26:55
【问题描述】:

我正试图围绕 .NET MVC5 路由展开思考。

我有一个表格:

@using (Html.BeginForm("ProductsCheaperThan", "Home", FormMethod.Post))
{
    <input type="text" name="comparisonPrice" />
    <button type="submit">Search!</button>
}

我有一个控制器Home 和一个动作ProductsCheaperThan,它接受一个参数comparisonPrice

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,但它使用了一个查询字符串,这并不是我想要的。

谁能帮我把我的网址弄对吗?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-5 asp.net-mvc-routing


    【解决方案1】:

    您应该将[HttpPost] 属性添加到您的操作中

    [HttpPost]
    public ActionResult ProductsCheaperThan(decimal comparisonPrice)
    {
        ViewBag.FilterPrice = comparisonPrice;
        var resultSet = new ProductService().GetProductsCheaperThan(comparisonPrice);
        return View(resultSet);
    }
    

    【讨论】:

    • 恐怕这行不通,有两个原因。一,我最终得到的 URL 仍然是 http://localhost:1959/Home/ProductsCheaperThan 而不是 http://localhost:1959/Home/ProductsCheaperThan/20,其次,任何从书签返回到该 URL 的人都将无法获取该页面,因为他们会使用 GET 来访问它而不是 POST。
    【解决方案2】:

    一种选择是使用 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>
    }
    

    以上脚本将导致 - http://localhost:1655/PriceToCompare/Home/123

    【讨论】:

      【解决方案3】:

      我认为你可以使用重载来指定你的路由值:

      @using (Html.BeginForm("Login", "Account", new { comparisonPrice= "20" })) { ... }

      【讨论】:

      • 这总是会导致~/Home/ProductsCheaperThan/20(它永远不会反映文本框中的值!)
      • 哦,对不起... MVC 应该自动将您的文本框值绑定到动作方法参数,因为它们的名称是匹配的。确保您的方法中有 [HttpPost]。我注意到在您的路线设置中,您在 url 中设置了硬编码的控制器和操作方法名称。路由 url 设置应该是这样的: url: "{controller}/{action}/{comparisonPrice}",默认值:new { controller = "Home", action = "ProductsCheaperThan", comparePrice= UrlParameter.Optional }
      猜你喜欢
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 2011-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多