2012-11-16 33 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 ... 
    } 
} 
相關問題