ASP.NET MVC查询字符串未在Url中显示

时间:2016-05-05 14:31:08

标签: c# asp.net asp.net-mvc routes

@using (Ajax.BeginForm("Search", "Filter", new { Area = "Music" }, new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "body-wrapper", OnSuccess = "updateHistory" }, new { @id = "search" }))
{
      <div>
           <i class="fa fa-search"></i>
           <input id="searchString" name="searchString" type="search" placeholder="Search">
      </div>
}

区域注册:

 context.MapRoute(
     "Music_default",
     "Music/{controller}/{action}/{category}",
     defaults: new { controller = "Home", action = "Index", category = UrlParameter.Optional }
 );

全球路线配置:

routes.MapRoute(
     name: "Default",
     url: "{area}/{controller}/{action}/{category}",
     defaults: new { area = "Music", controller = "Home", action = "Index", category = UrlParameter.Optional }
).DataTokens.Add("area", "Music");

控制器:

public ActionResult Search(string searchString)
{
    //Do search stuff
}

每当用户输入搜索输入并提交时,网址始终为:/Music/Filter/Search,而不是/Music/Filter/Search/{queryStringHere}

如何向用户显示用户输入的查询? searchString正确绑定,但只是没有显示在网址中。

以下是我在区域注册中尝试过的内容,但由于某种原因它没有映射到这个:

context.MapRoute(
     "Music_Search",
     "Music/Filter/Search/{searchString}",
     defaults: new { controller = "Filter", action = "Search" }
);

当我输入搜索字词'Maid'时,根据RouteDebugger生成的Url是:

生成的网址:/ User / Filter / Search?searchString = Maid&amp; X-Requested-With = XMLHttpRequest&amp; _ = 1462458566832

修改 RouteDebugger图像,它不会调用正确的路由配置,因为它似乎没有将查询字符串附加到RouteData: enter image description here

2 个答案:

答案 0 :(得分:1)

浏览器对您的路由定义(服务器端代码)一无所知,并且<form>method="get"的值始终作为查询字符串值添加。

除非您在User/Filter/Search/Maid方法中添加路由值,否则无法生成BeginForm(),或者您要使用javascript / jquery更新action属性在提交表单之前<form>

答案 1 :(得分:0)

试试这个。更改您的Route以接受可选的searchString参数:

routes.MapRoute(
     name: "Default",
     url: "{area}/{controller}/{action}/{category}/{searchString}",
     defaults: new { area = "Music", controller = "Home", action = "Index", category = UrlParameter.Optional, searchString = UrlParameter.Optional }
).DataTokens.Add("area", "Music");

然后在Ajax.BeginForm传递searchString作为第三个参数:

@using (Ajax.BeginForm("Search", "Filter", new { Area = "Music" }, new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "body-wrapper", OnSuccess = "updateHistory" }, new { @id = "search" }))
{
  // Or pass the value as input
  <input type="text" id="searchString" name="searchString" value="@item.Quantity"/>
 <input type="submit" />
}