ASP.Net MVC路由无法正常工作

时间:2010-11-04 11:34:53

标签: asp.net-mvc asp.net-mvc-routing

我们的Global.asax.cs文件中有几条路线,但其中一条路线显然没有被使用。

// 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 });

当我们在搜索表单中搜索哪个操作属性为“/搜索”时,用户将被发送到主页,地址栏中的URL为“/Search?query=example+search".

使用以下代码构建表单操作属性:

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

似乎对我而言,但操作名称应该是“/ search”而不是“/ Search”,对吗?

3 个答案:

答案 0 :(得分: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将为您完成的。这是允许绑定获取值并将其正确传递给控制器​​的原因。

答案 1 :(得分:2)

我总觉得这个工具在调试路由方面非常有帮助。 Route Debugger

答案 2 :(得分:1)

尝试"search/{query}"匹配案例=&gt; "Search/{query}"

您对表单标记的操作是/Search/Index,它将与您的Search/{query}路由匹配,但您的查询将是索引。但是,如果路由末尾有?query=example+search,则搜索路由将不知道如何处理该查询参数。我只是将表单标记上的action属性更新为/Search而不使用URL帮助程序。