2

我还没有做任何花哨的路由模式,只是基本的控制器、动作、id 样式。

但是,我的行为似乎从未通过 id。当我在任何一项操作中设置断点时,id 参数的值为 null。是什么赋予了?

全球.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 上的 Index() 操作:

/// <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 参数的值为aways null!!!啊!愚蠢的是,当我使用 Phil Haack 的 Route Debugger 时,我可以清楚地看到调试器看到了 id。什么废话?!

4

2 回答 2

9

我认为您是控制器方法的参数名称需要与路由字符串中的名称匹配。因此,如果这是在您的 global.asax 中:

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

您的控制器方法应如下所示(注意参数名称是“id”,而不是“tenantId”):

public ActionResult Index(int? id)
于 2009-11-10T02:49:36.507 回答
5

将方法更改为Index( int? id )而不是Index( int? tenantId ),它将通过路由填充。

在您的路线中,您已将变量声明为“id”,但您随后尝试使用“tenantId”访问它。例如,如果您访问一个页面并添加查询字符串,则tenantId 将被填充?tenantId=whatever

ASP.NET MVC 大量使用反射,因此在此类情况下,您为方法和参数指定的名称很重要。

于 2009-11-10T02:50:32.397 回答