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) 
    { 
     // ... 
    } 
相关问题