以mvc格式显示特定格式的查询字符串

时间:2016-11-01 10:37:07

标签: asp.net-mvc query-string

当我们使用get方法提交表单时,它将参数作为查询字符串传递如下: http://localhost:2564/Blog?SearchManufacturer=land

但是,我想显示如下的查询字符串:

http://localhost:2564/Blog/SearchManufacturer/land

我试过下面的代码。但它仍然使用查询字符串传递。

@using (Html.BeginForm("Index", "Blog", new { CurrentFilter = Model.SearchManufacturer }, FormMethod.Get))
  {
     <div class="form-group col-lg-4 col-md-6 col-sm-6 col-lg-12">
       <label>Search Manufacturer</label>
@Html.TextBoxFor(x => x.SearchManufacturer, new { @class = "form-control" })
</div>                                                
<div class="form-group col-lg-4 col-md-6 col-sm-6 col-lg-12">
<input type="submit" value="Search" class="submit" />
</div>
}

另外,在route.config中,我使用了不同的路由组合,如下所示。

  routes.MapRoute("Blog", "Blog/SearchManufacturer/{SearchManufacturer}", defaults: new { controller = "Blog", action = "Index" });            
            routes.MapRoute("BlogbyPageSortandFilter", "Blog/Page/{page}/CurrentFilter/{currentFilter}/SortBy/{sort}", defaults: new { controller = "Blog", action = "Index" });
            routes.MapRoute("BlogbyPageandSort", "Blog/Page/{page}/SortBy/{sort}", defaults: new { controller = "Blog", action = "Index" });
            routes.MapRoute("BlogbyPageandFilter", "Blog/Page/{page}/CurrentFilter/{currentFilter}", defaults: new { controller = "Blog", action = "Index" });
            routes.MapRoute("BlogbySortandFilter", "Blog/SortBy/{sort}/CurrentFilter/{currentFilter}", defaults: new { controller = "Blog", action = "Index" });
            routes.MapRoute("SortBlog", "Blog/SortBy/{sort}", defaults: new { controller = "Blog", action = "Index" });
            routes.MapRoute("BlogbyPage", "Blog/Page/{page}", defaults: new { controller = "Blog", action = "Index" });
            routes.MapRoute("BlogbyFilter", "Blog/CurrentFilter/{currentFilter}", defaults: new { controller = "Blog", action = "Index" });

这些路由用于使用Pagedlist.mvc进行排序,分页和过滤。所有这些都很好。但搜索不是像路由一样传递参数。它将参数作为查询字符串传递。

请帮我解决这个问题。

由于

拉​​莉莎

1 个答案:

答案 0 :(得分:0)

如果您的表单方法设置为GET类型,则在提交表单时,表单数据将作为查询字符串值(以?开头)附加到操作属性URL。这是浏览器所做的事情。您的asp.net mvc路由无法做任何事情。

如果您在提交表单时绝对需要/Blog/SearchManufacturer/land网址,则可以使用客户端javascript劫持表单提交事件,并根据需要更新网址。下面的代码将为您提供所需的输出。

$(function () {

    $("#searchFrm").submit(function (e) {
        e.preventDefault();
        var formAction = $(this).attr("action");
        if (!formAction.endsWith('/')) {
            formAction += '/';
        }
        var url = formAction +'SearchManufacturer/'+ $("#SearchManufacturer").val();
        window.location.href = url;
    });

});

假设您的表单标记的Id值为“searchFrm”

@using (Html.BeginForm("Index", "Blog",FormMethod.Get,new { id="searchFrm"}))
{
  // Your existing code goes here
}