如何组织控制器类和动作方法?

时间:2012-10-13 15:49:28

标签: asp.net-mvc controller asp.net-mvc-4 actionmethod code-standards

假设我正在开设汽车门户网站。要搜索新车,用户会提供以下信息:

  • 品牌
  • 模型
  • ModelVersion
  • FuelType
  • 预算

业务规则:

  1. 如果用户仅选择品牌:显示所选品牌所有型号的品牌列表页面
  2. 如果用户选择品牌和型号:显示型号列表页面
  3. 如果用户选择Brand + Model + Model版本:显示模型版本详细信息页面。
  4. 如果用户选择燃料类型或预算:显示品牌列表页面。
  5. 现在我有两种方法来定义控制器和动作。

    方法1:具有多种操作方法的一个Controller类

    Controller Class : CarSearchmanager
    with following are Action Methods:
            - SearchNewCar(int Barnd,int Model.......)
              Depending on user selection this method will redirect control to following  
              action method:
    
            - BrandListing(int BrandID......)
            - ModelListing(int BrandID,intModelID.....)
            - ModelVersionDetails((int BrandID,intModelID,int ModelVersionID....)
    

    方法2:多控制器类

    Controller Class : CarSearchmanager
    
    Following are Action Methods:
            - SearchNewCar(int Barnd,int Model.......)
              Depending on user selection this method will redirect control to following 
              controller action method:
    
    Then I will have separate controller class and action method for each of the pages like 
    bellow:
    
        - BrandListing
        - ModelListing
        - ModelVersionDetails
    

    我对如何组织控制器类和操作方法感到很困惑。有没有最佳实践文件?请向我推荐一个。

2 个答案:

答案 0 :(得分:1)

我认为没有定义最佳版本。以这样的方式定义它,让您感觉更干净,更有条理。根据我对你的要求的理解,我可以这样定义

BrandController

行动方法

  • ListForFuleAndBudget(string fuelType,string budget)
  • List(string brandName)

ModelController

动作方法

  • List(string brand,string model)
  • Details(string brand, string model, string version)

现在,如果您想要一个不需要动作方法名称的好网址,那么(例如:详细信息)您可以在通用路由定义之前在global.asax中注册路由时定义您的漂亮网址。

routes.MapRoute("list", "model/{brand}/{model}",
               new { controller = "brand", action = "List");

routes.MapRoute("list", "model/{brand}/{model}/{version}",
               new { controller = "brand", action = "details");

//default route definition goes here

现在yoursitename/model/honda/camry会将用户带到list操作方法和 yoursitename/model/honda/camry/lx会将他们带到details操作方法。

答案 1 :(得分:0)

我的建议是将它放在同一个控制器中 由于这是将使用的搜索功能 在类似的背景下。使用方法重载和在 相应的方法返回特定的视图。