2012-11-16 34 views
1

我一直在研究这个在同一个文件夹视图。我发现“MVCS区”,但我还是不能做什么我要找的。不同的控制器对asp.net MVC4

我的看法: 查看/ 学生/课程 学生/信息 学生/状态 学生/ GeneralSituation 等等,等等......

控制器:

控制器/学生

我想要做的是:

我不想让所有的代码只有一个“学生”控制器有很多意见。 任何提示就如何我可以“分裂”我在几个文件中的控制器? 我只是在寻找最简单的方法,我不想作大的修改,我的项目。

我使用MVC4。

提前感谢!..

即插即用

回答

1

,你可以做一个分部类StudentController:

您的文件夹/文件应该是这样的:

Controllers 
    StudentController 
    StudentController.Status.cs 
    StudentController.GeneralSituation.cs 
    StudentController.Course.cs 

代码将是:

StudentController.Status.cs:

public partial class StudentController 
{ 
    [Actions relevant for Status of a student] 
} 

StudentController.GeneralSituation.cs:

public partial class StudentController 
{ 
    [Actions relevant for General Situation of a student] 
} 
2

为什么不干脆让部分控制器类,因此在一堆物理文件分割一个控制器?

另外,你是什么意思“来自很多意见的代码”?您是否正在使用单独的服务层并在那里执行业务逻辑,因为这是最佳实践。控制器的意思是非常轻巧,沿此线路代码:

public ActionMethod DoSomething() 
{ 
    StudentViewModel vm = _studentService.GetSomeData(); 
    return View(vm); 
} 
0

有什么理由区的不工作?从你所描述的,我不明白他们为什么不会。

- Areas 
    - Students 
     - Controllers 
      HomeController   Handles base /Students/ route 
      InformationController ~/Students/Information/{action}/{id} 
      StatusController   ~/Students/Status/{action}/{id} 
      ... 
     - Models 
     - Views 
      Home/ 
      Information/ 
      Status/ 
      ... 
      Shared/  Stick common views in here 

如果你一个怪物控制器(或谐音)的参数设置,你的控制器应在它很少有实际的“查看代码”。保留所有这些以查看模型 - 控制器只需传递所需的资源即可构建视图数据,从而保持控制器精简。

也就是说,

public class StudentController 
{ 
    ... 

    // Actually I prefer to bind the id to a model and handle 404 
    // checking there, vs pushing that boiler plate code further down 
    // into the controller, but this is just a quick example. 

    public ActionResult Information(int id) 
    { 
     return View(new InformationPage(this.StudentService, id)); 
    } 
} 

然后,InformationPage是您的模型将处理扩建适用于该视图中的所有信息之一。

public class InformationPage 
{ 
    public Student Student { get; set; } 

    public InformationPage(StudentService service, int studentId) 
    { 
     Student = service.FindStudent(studentId); 
     ... Other view data ... 
    } 
} 
相关问题