2010-11-04 120 views
1

我们在Global.asax.cs文件中有几条路线,但其中一条路线显然未被使用。ASP.Net MVC路线不能正常工作

// Search (NOT working). 
routes.MapRoute(
     "Search", 
     "search/{query}", 
     new { controller = "Search", action = "Index" }); 

// Homepage (I believe the problem could be here, but not sure). 
routes.MapRoute(
     "MainIndex", 
     "{language}", 
     new { controller = "Main", action = "Index", language = string.Empty }); 

当我们在搜索形式action属性“/搜索”的搜索,用户被发送到网页,并在地址栏中的URL是“/搜索?查询=例如+搜索” 。

形式action属性建立在使用此代码:

<form id="form1" action="<%= Url.Action("Index", "Search") %>"> 

似乎是正确的我,但动作的名称应该是“/搜索”,而不是“/搜索”,对不对?

+0

我假设搜索路径在您的代码中的MainIndex路由之前列出*(正如您在自己的文章中所见),正确吗? – 2010-11-04 11:55:49

+0

是的,赫克托。搜索路线列出了MainIndex路线__before__。 – 2010-11-04 14:11:02

回答

1

尝试使"search/{query}"匹配的情况下=>"Search/{query}"

嗯,你在表单标签的行动是/Search/Index,这将符合您Search/{query}路线,但您的查询将是指数。但是,在路由结束时,?query=example+search搜索路径将不知道如何处理该查询参数。我只是将表单标签上的action属性更新为/Search,而不是使用URL助手。

+0

不,那不是因为路线做得很好而导致错误的原因。由于路径要求提交表单之前不存在的查询参数(“/ search”不对应于路由“search/{query}”),所以只有路由搜索在制作表单的action属性时没有被捕获)。但是,谢谢!好的尝试+1 – 2010-11-04 11:46:00

3

我只是想你的路线有以下几种观点

<form id="form1" method="post" action="<%= Url.Action("Index", "Search") %>"> 
Enter something: <input type="text" name="query" id="query" value="hello" /> 
<input type="submit" /> 
</form> 

和控制器这样

public ActionResult Index(string query) 
{ 
    return View(); 
} 

和它的作品确定。注意(1)我使用method = post和(2)该文本框的名称和ID都设置为“query”,这就是Html.TextBox为您所做的事情。这是允许绑定获取值并将其正确传递给控制器​​的原因。