2010-04-29 41 views
0

我使用ASP.MVC並試圖瞭解一個索引視圖...隨地吐痰了使用參數

我有以下控制器

// get all authors 
    public ActionResult Index() 
    { 
     var autores = autorRepository.FindAllAutores(); 

     return View("Index", autores); 
    } 

    // get authors by type 
    public ActionResult Index(int id) 
    { 
     var autores = autorRepository.FindAllAutoresPorTipo(id); 

     return View("Index", autores); 
    } 

如果我嘗試http://server/Autor/1我得到一個404錯誤。這是爲什麼?

我甚至試圖創建一個特定的方法ListByType(INT ID)和對應的觀點,但是,這並不工作太(網址:http://server/Autor/ListByType/1

任何想法?

編輯哦,http://server/Autor工作得很好。沒有參數的方法正在正確地吐出我的視圖。

回答

2

假設你的類被稱爲AutorController,並假設你有

{controller}/{action}/{id} 

默認路由配置您應該能夠要求

/Autor/Index/<anything> 

但是,你似乎是有點糊塗上行動方法。你可以結合你的操作方法如下所示:

public ActionResult Index(int? id) 
{ 
    var autores; // I know this wont compile - but without knowing what type FindAllAutoRes returns, I can't make a specific type for this example 
    if(id.HasValue) 
     autores = autorRepository.FindAllAutoresPorTipo(id); 
    else 
     autores = autorRepository.FindAllAutores(); 

    return View(autores); // Will automatically select the 'Index' View 
} 

MVC將選擇對應於您的路由數據的第一個有效的操作方法 - 因此,如果您的請求/作者日期/索引/ 3,你會得到的第一個動作方法,但由於它沒有參數,id路由數據不會綁定任何東西。

+0

我試過這個,但我仍然得到404錯誤。我的路由配置是默認的控制器/操作/ ID。 我會繼續挖掘。謝謝! – 2010-04-29 17:10:08