0

我有一個ProdcutsController,其中有2個Action方法。索引和詳細信息。 索引將返回產品清單,詳細信息將返回選定產品ID的詳細信息。ASP.NET MVC3:ActionMethod具有相同名稱和不同參數的List和Details視圖

所以我的網址都是這樣

sitename/Products/ 

將加載索引視圖來顯示的產品列表。

sitename/Products/Details/1234 

將加載詳細信息視圖顯示1234

現在我要避免從我的第二個網址的「詳細信息」字產品的詳細信息。所以,它應該像

sitename/Products/1234 

我試圖從「詳細信息」,以「索引」,在它的參數重命名我的操作方法。但它給我的錯誤「Method is is ambiguous

我想這

public ActionResult Index() 
{ 
    //code to load Listing view 
} 
public ActionResult Index(string? id) 
{ 
    //code to load details view 
} 

我得到這個錯誤現在

The type 'string' must be a non-nullable value type in order to use 
it as parameter 'T' in the generic type or method 'System.Nullable<T> 

意識到,它不支持方法重載!我該如何處理?我應該更新我的路線定義嗎?

回答

1

使用此:

public ActionResult Index(int? id) 
{ 
    //code to load details view 
} 

假設值是整數類型。

這是另一種選擇:

public ActionResult Index(string id) 
{ 
    //code to load details view 
} 

string是引用類型,以便一個null可以已經分配給它,而無需一個Nullable<T>

+0

俄德路線:第一個給我404錯誤,第二個給我ambigous指數方法的錯誤。我應該在global.asax中更新我的路線註冊嗎? – Happy 2011-12-25 21:22:43

+0

@快樂 - 你有什麼其他'索引'動作? – Oded 2011-12-26 08:20:39

0

您可以使用一個Action方法。

喜歡的東西:

public ActionResult Index(int? Id) 
{ 
    if(Id.HasValue) 
    { 
    //Show Details View 
    } 
    else 
    { 
    //Show List View 
    } 
} 
+0

這給了我一個資源無法找到(404)找不到的錯誤。我應該更新global.asax中的內容嗎? – Happy 2011-12-25 21:13:24

0

您可以創建兩個路由和使用路由約束:

的Global.asax

 routes.MapRoute(
      "Details", // Route name 
      "{controller}/{id}", // URL with parameters 
      new { controller = "Products", action = "Details" }, // Parameter defaults 
      new { id = @"\d+" } 
     ); 

     routes.MapRoute(
      "Default", // Route name 
      "{controller}/{action}/{id}", // URL with parameters 
      new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
     ); 

第一個路由出現問題,需要ID有一個或約束更多數字。由於這種約束也不會趕上像~/home/about

的ProductsController

public ActionResult Index() 
    { 
     // ... 
    } 

    public ActionResult Details(int id) 
    { 
     // ... 
    } 
相關問題