2009-11-10 100 views
2

我還沒有做任何奇特的路線模式,只是基本的控制器,動作,身份證樣式。asp.net mvc id不從路由中拉出?

但是,我的行爲似乎沒有通過id。當我在任何一個動作中插入一個斷點時,id參數的值爲null。是什麼賦予了?

的Global.asax.cs:

public class MvcApplication : System.Web.HttpApplication 
{ 
    public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapRoute(
      "Default",             // Route name 
      "{controller}/{action}/{id}",        // URL with parameters 
      new { controller = "Tenants", action = "Index", id = "" } // Defaults 
     ); 
    } 

    protected void Application_Start() 
    { 
     RegisterRoutes(RouteTable.Routes); 
     //RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes); 
     ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory()); 
    } 

    protected void Application_AuthenticateRequest() 
    { 
     if (User != null) 
      Membership.GetUser(true); 
    } 
} 

指數()上TenantsController.cs行動:

/// <summary> 
    /// Builds the Index view for Tenants 
    /// </summary> 
    /// <param name="tenantId">The id of a Tenant</param> 
    /// <returns>An ActionResult representing the Index view for Tenants</returns> 
    public ActionResult Index(int? tenantId) 
    { 
     //a single tenant instance, requested by id 
     //always returns a Tenant, even if its just a blank one 
     Tenant tenant = _TenantsRepository.GetTenant(tenantId); 

     //returns a list of TenantSummary 
     //gets every Tenant in the repository 
     List<TenantSummary> tenants = _TenantsRepository.TenantSummaries.ToList(); 

     //bilds the ViewData to be returned with the View 
     CombinedTenantViewModel viewData = new CombinedTenantViewModel(tenant, tenants); 

     //return index View with ViewData 
     return View(viewData); 
    } 

的tenantId參數的值是贈品空!哎呀!愚蠢的是,當我使用Phil Haack的Route Debugger時,我可以清楚地看到調試器看到了這個id。什麼廢話?!

回答

8

我想你是控制器方法的參數名稱需要匹配路由字符串中的名稱。因此,如果這是你的Global.asax:

routes.MapRoute(
     "Default",             // Route name 
     "{controller}/{action}/{id}",        // URL with parameters 
     new { controller = "Tenants", action = "Index", id = "" } // Defaults 
); 

你的控制器方法應該是這樣的(注意參數的名字是「身份證」,而不是「tenantId」):

public ActionResult Index(int? id) 
+0

你和Stephen的回答幾乎完全相同,你的答案都是正確的。然而,接受MrDustpan先生是因爲他早1分鐘。斯蒂芬很好的解釋。 – NovaJoe

5

變化的方法到Index(int? id)而不是Index(int? tenantId),它將通過路由填充。

在您的路線中,您已聲明變量被命名爲「id」,但您正在嘗試使用「tenantId」訪問它。例如,如果您訪問頁面並添加查詢字符串?tenantId=whatever,tenantId將被填充。

ASP.NET MVC大量使用了反射,因此在這些情況下,您給方法和參數的名字很重要。

+0

正確!有人在MS MVC論壇上向我指出了這一點。這是一個肯定的額頭拍打時刻。我只是改變了動作的參數名稱以匹配路由的「ID」。謝謝! – NovaJoe