2010-11-04 101 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爲您所做的事情。這是允許綁定獲取值並將其正確傳遞給控制器​​的原因。