【问题标题】:How To Prevent Query String but use routes in Html.BeginForm (GET)?如何防止查询字符串但在 Html.BeginForm (GET) 中使用路由?
【发布时间】:2017-12-13 03:58:41
【问题描述】:

我有一个搜索页面。我是一个搜索面板,我填充了一个这样的模型:

public class SearchVm
{
    public long? CategoryId { get; set; }
    public long? ProductId { get; set; }
    public DateTime? FromDate { get; set; }
    public DateTime? ToDate { get; set; }
    public string Text { get; set; }
}

由于我们对 SEO 感兴趣,所以我想使用 GET 方法来获取搜索结果。所以我的表格是这样的:

@using (@Html.BeginForm("Search", "Products", FormMethod.Get))
{...}

这里是动作签名:

 public ActionResult Search(SearchVM esm){...}

但是我的 URL 太丑了,如果我没有在 URL 中填写属性“IT IS”作为查询字符串:

http://localhost:8080/Products/Search?CategoryId=2&ProductId=&Text=&FromDate=&ToDate=

在这个网址中,我只是填写了“CategoryId”! 但是我怎样才能为我的搜索设置一个动态路径

"Products/Search/cat{CategoryId}/prod{ProductId}/{Text}/{FromDate}/{ToDate}"
"Products/Search/prod{ProductId}/{Text}/{FromDate}/{ToDate}"
"Products/Search/prod{ProductId}"
"Products/Search/cat{CategoryId}"
"Products/Search/{FromDate}/{ToDate}"
"Products/Search/{FromDate}"

实际上我怎样才能将所有这些组合重定向到相同的操作

【问题讨论】:

  • 您可以为您的操作显示签名吗?
  • 亲爱的@CodingYoshi,我在帖子中添加了签名
  • 请阅读this 的答案和所有的cmets,这样您就可以了解为什么querystring 更适合用户输入的数据。如果您不希望查询字符串中有空项目,则需要为此编写 javascript,因为您只会在提交表单之前知道它们是否为空。如果您搜索remove empty querystring parameters with javascript,您将能够在网上找到如何做到这一点

标签: c# search model-view-controller routing


【解决方案1】:

实际上,您应该为搜索字段使用查询参数,而不是路径参数。但是,如果您坚持,请在您的操作中使用路由属性(System.Web.Mvc.Route),如下所示:

Route("Products/Search/{FromDate}")

使用您想要触发相关“ActionResult”方法的所有路由

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 2011-10-19
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多