2

基本的なコントローラー、アクション、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 での 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 パラメータの値が 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
  );

コントローラメソッドは次のようになります(パラメータ名は「tenantId」ではなく「id」であることに注意してください)。

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 に答える