- Understanding Models, Views, and Controllers (C#)
- The Sample ASP.NET MVC Application
- A URL Does Not Equal a Page
- Understanding ASP.NET Routing
- Understanding Controllers
- Understanding Views
- Understanding Models
- Общие сведения о моделях, представлениях и контроллерах (C#) Understanding Models, Views, and Controllers (C#)
- Пример приложения ASP.NET MVC The Sample ASP.NET MVC Application
- URL-адрес не равен странице A URL Does Not Equal a Page
- Основные сведения о маршрутизации ASP.NET Understanding ASP.NET Routing
- Основные сведения об контроллерах Understanding Controllers
- Основные сведения о представлениях Understanding Views
- Основные сведения о моделях Understanding Models
Understanding Models, Views, and Controllers (C#)
Confused about Models, Views, and Controllers? In this tutorial, Stephen Walther introduces you to the different parts of an ASP.NET MVC application.
This tutorial provides you with a high-level overview of ASP.NET MVC models, views, and controllers. In other words, it explains the M’, V’, and C’ in ASP.NET MVC.
After reading this tutorial, you should understand how the different parts of an ASP.NET MVC application work together. You should also understand how the architecture of an ASP.NET MVC application differs from an ASP.NET Web Forms application or Active Server Pages application.
The Sample ASP.NET MVC Application
The default Visual Studio template for creating ASP.NET MVC Web Applications includes an extremely simple sample application that can be used to understand the different parts of an ASP.NET MVC application. We take advantage of this simple application in this tutorial.
You create a new ASP.NET MVC application with the MVC template by launching Visual Studio 2008 and selecting the menu option File, New Project (see Figure 1). In the New Project dialog, select your favorite programming language under Project Types (Visual Basic or C#) and select ASP.NET MVC Web Application under Templates. Click the OK button.
Figure 01: New Project Dialog (Click to view full-size image)
When you create a new ASP.NET MVC application, the Create Unit Test Project dialog appears (see Figure 2). This dialog enables you to create a separate project in your solution for testing your ASP.NET MVC application. Select the option No, do not create a unit test project and click the OK button.
Figure 02: Create Unit Test Dialog (Click to view full-size image)
After the new ASP.NET MVC application is created. You will see several folders and files in the Solution Explorer window. In particular, you’ll see three folders named Models, Views, and Controllers. As you might guess from the folder names, these folders contain the files for implementing models, views, and controllers.
If you expand the Controllers folder, you should see a file named AccountController.cs and a file named HomeController.cs. If you expand the Views folder, you should see three subfolders named Account, Home and Shared. If you expand the Home folder, you’ll see two additional files named About.aspx and Index.aspx (see Figure 3). These files make up the sample application included with the default ASP.NET MVC template.
Figure 03: The Solution Explorer Window (Click to view full-size image)
You can run the sample application by selecting the menu option Debug, Start Debugging. Alternatively, you can press the F5 key.
When you first run an ASP.NET application, the dialog in Figure 4 appears that recommends that you enable debug mode. Click the OK button and the application will run.
Figure 04: Debugging Not Enabled dialog (Click to view full-size image)
When you run an ASP.NET MVC application, Visual Studio launches the application in your web browser. The sample application consists of only two pages: the Index page and the About page. When the application first starts, the Index page appears (see Figure 5). You can navigate to the About page by clicking the menu link at the top right of the application.
Figure 05: The Index Page (Click to view full-size image)
Notice the URLs in the address bar of your browser. For example, when you click the About menu link, the URL in the browser address bar changes to /Home/About.
If you close the browser window and return to Visual Studio, you won’t be able to find a file with the path Home/About. The files don’t exist. How is this possible?
A URL Does Not Equal a Page
When you build a traditional ASP.NET Web Forms application or an Active Server Pages application, there is a one-to-one correspondence between a URL and a page. If you request a page named SomePage.aspx from the server, then there had better be a page on disk named SomePage.aspx. If the SomePage.aspx file does not exist, you get an ugly 404 — Page Not Found error.
When building an ASP.NET MVC application, in contrast, there is no correspondence between the URL that you type into your browser’s address bar and the files that you find in your application. In an ASP.NET MVC application, a URL corresponds to a controller action instead of a page on disk.
In a traditional ASP.NET or ASP application, browser requests are mapped to pages. In an ASP.NET MVC application, in contrast, browser requests are mapped to controller actions. An ASP.NET Web Forms application is content-centric. An ASP.NET MVC application, in contrast, is application logic centric.
Understanding ASP.NET Routing
A browser request gets mapped to a controller action through a feature of the ASP.NET framework called ASP.NET Routing. ASP.NET Routing is used by the ASP.NET MVC framework to route incoming requests to controller actions.
ASP.NET Routing uses a route table to handle incoming requests. This route table is created when your web application first starts. The route table is setup in the Global.asax file. The default MVC Global.asax file is contained in Listing 1.
Listing 1 — Global.asax
When an ASP.NET application first starts, the Application_Start() method is called. In Listing 1, this method calls the RegisterRoutes() method and the RegisterRoutes() method creates the default route table.
The default route table consists of one route. This default route breaks all incoming requests into three segments (a URL segment is anything between forward slashes). The first segment is mapped to a controller name, the second segment is mapped to an action name, and the final segment is mapped to a parameter passed to the action named Id.
For example, consider the following URL:
This URL is parsed into three parameters like this:
The Default route defined in the Global.asax file includes default values for all three parameters. The default Controller is Home, the default Action is Index, and the default Id is an empty string. With these defaults in mind, consider how the following URL is parsed:
This URL is parsed into three parameters like this:
Finally, if you open an ASP.NET MVC Application without supplying any URL (for example, http://localhost ) then the URL is parsed like this:
The request is routed to the Index() action on the HomeController class.
Understanding Controllers
A controller is responsible for controlling the way that a user interacts with an MVC application. A controller contains the flow control logic for an ASP.NET MVC application. A controller determines what response to send back to a user when a user makes a browser request.
A controller is just a class (for example, a Visual Basic or C# class). The sample ASP.NET MVC application includes a controller named HomeController.cs located in the Controllers folder. The content of the HomeController.cs file is reproduced in Listing 2.
Listing 2 — HomeController.cs
Notice that the HomeController has two methods named Index() and About(). These two methods correspond to the two actions exposed by the controller. The URL /Home/Index invokes the HomeController.Index() method and the URL /Home/About invokes the HomeController.About() method.
Any public method in a controller is exposed as a controller action. You need to be careful about this. This means that any public method contained in a controller can be invoked by anyone with access to the Internet by entering the right URL into a browser.
Understanding Views
The two controller actions exposed by the HomeController class, Index() and About(), both return a view. A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an ASP.NET MVC application.
You must create your views in the right location. The HomeController.Index() action returns a view located at the following path:
The HomeController.About() action returns a view located at the following path:
In general, if you want to return a view for a controller action, then you need to create a subfolder in the Views folder with the same name as your controller. Within the subfolder, you must create an .aspx file with the same name as the controller action.
The file in Listing 3 contains the About.aspx view.
Listing 3 — About.aspx
If you ignore the first line in Listing 3, most of the rest of the view consists of standard HTML. You can modify the contents of the view by entering any HTML that you want here.
A view is very similar to a page in Active Server Pages or ASP.NET Web Forms. A view can contain HTML content and scripts. You can write the scripts in your favorite .NET programming language (for example, C# or Visual Basic .NET). You use scripts to display dynamic content such as database data.
Understanding Models
We have discussed controllers and we have discussed views. The last topic that we need to discuss is models. What is an MVC model?
An MVC model contains all of your application logic that is not contained in a view or a controller. The model should contain all of your application business logic, validation logic, and database access logic. For example, if you are using the Microsoft Entity Framework to access your database, then you would create your Entity Framework classes (your .edmx file) in the Models folder.
A view should contain only logic related to generating the user interface. A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control). Everything else should be contained in the model.
In general, you should strive for fat models and skinny controllers. Your controller methods should contain only a few lines of code. If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder.
Общие сведения о моделях, представлениях и контроллерах (C#) Understanding Models, Views, and Controllers (C#)
Не путать с моделями, представлениями и контроллерами? Confused about Models, Views, and Controllers? В этом руководстве Стивен Вальтер содержит сведения о различных частях приложения ASP.NET MVC. In this tutorial, Stephen Walther introduces you to the different parts of an ASP.NET MVC application.
В этом учебнике представлен общий обзор моделей, представлений и контроллеров ASP.NET MVC. This tutorial provides you with a high-level overview of ASP.NET MVC models, views, and controllers. Иными словами, здесь объясняются M, V и C в ASP.NET MVC. In other words, it explains the M’, V’, and C’ in ASP.NET MVC.
Прочитав этот учебник, вы должны понимать, как различные части приложения MVC ASP.NET работают вместе. After reading this tutorial, you should understand how the different parts of an ASP.NET MVC application work together. Следует также понимать, как архитектура приложения ASP.NET MVC отличается от приложения ASP.NET Web Forms или приложения Active Server Pages. You should also understand how the architecture of an ASP.NET MVC application differs from an ASP.NET Web Forms application or Active Server Pages application.
Пример приложения ASP.NET MVC The Sample ASP.NET MVC Application
Шаблон по умолчанию Visual Studio для создания веб-приложений ASP.NET MVC включает в себя очень простой пример приложения, который можно использовать для понимания различных частей приложения ASP.NET MVC. The default Visual Studio template for creating ASP.NET MVC Web Applications includes an extremely simple sample application that can be used to understand the different parts of an ASP.NET MVC application. В этом руководстве мы используем это простое приложение. We take advantage of this simple application in this tutorial.
Вы создадите новое приложение ASP.NET MVC с шаблоном MVC, запустив Visual Studio 2008 и выбрав файл параметров меню, новый проект (см. рис. 1). You create a new ASP.NET MVC application with the MVC template by launching Visual Studio 2008 and selecting the menu option File, New Project (see Figure 1). В диалоговом окне Новый проект выберите предпочитаемый язык программирования в разделе Типы проектов (Visual Basic или C#) и выберите веб-приложение ASP.NET MVC в разделе Шаблоны. In the New Project dialog, select your favorite programming language under Project Types (Visual Basic or C#) and select ASP.NET MVC Web Application under Templates. Нажмите кнопку «ОК». Click the OK button.
Рис. 01. диалоговое окно создания проекта (щелкните, чтобы просмотреть изображение с полным размером) Figure 01: New Project Dialog (Click to view full-size image)
При создании нового приложения ASP.NET MVC появляется диалоговое окно Создание проекта модульного теста (см. рис. 2). When you create a new ASP.NET MVC application, the Create Unit Test Project dialog appears (see Figure 2). Это диалоговое окно позволяет создать отдельный проект в решении для тестирования приложения ASP.NET MVC. This dialog enables you to create a separate project in your solution for testing your ASP.NET MVC application. Выберите вариант нет, не создавать проект модульного теста и нажмите кнопку ОК . Select the option No, do not create a unit test project and click the OK button.
Рис. 02. диалоговое окно «Создание модульного теста» (щелкните, чтобы просмотреть изображение с полным размером) Figure 02: Create Unit Test Dialog (Click to view full-size image)
После создания нового приложения MVC ASP.NET. After the new ASP.NET MVC application is created. В окне обозреватель решений вы увидите несколько папок и файлов. You will see several folders and files in the Solution Explorer window. В частности, вы увидите три папки с именами Models, Views и Controllers. In particular, you’ll see three folders named Models, Views, and Controllers. Как вы можете предположить из имен папок, эти папки содержат файлы для реализации моделей, представлений и контроллеров. As you might guess from the folder names, these folders contain the files for implementing models, views, and controllers.
Если развернуть папку Controllers, появится файл с именем AccountController.cs и файл с именем HomeController.cs. If you expand the Controllers folder, you should see a file named AccountController.cs and a file named HomeController.cs. Если развернуть папку Views, вы увидите три вложенных папки с именем Account, Home и Shared. If you expand the Views folder, you should see three subfolders named Account, Home and Shared. Если развернуть корневую папку, вы увидите два дополнительных файла с именами About. aspx и index. aspx (см. рис. 3). If you expand the Home folder, you’ll see two additional files named About.aspx and Index.aspx (see Figure 3). Эти файлы составляют пример приложения, который входит в состав шаблона по умолчанию ASP.NET MVC. These files make up the sample application included with the default ASP.NET MVC template.
Рис. 03. окно Обозреватель решений (щелкните, чтобы просмотреть изображение с полным размером) Figure 03: The Solution Explorer Window (Click to view full-size image)
Чтобы запустить пример приложения, выберите пункт меню Отладка, начать отладку. You can run the sample application by selecting the menu option Debug, Start Debugging. Кроме того, можно нажать клавишу F5. Alternatively, you can press the F5 key.
При первом запуске приложения ASP.NET открывается диалоговое окно на рис. 4, в котором рекомендуется включить режим отладки. When you first run an ASP.NET application, the dialog in Figure 4 appears that recommends that you enable debug mode. Нажмите кнопку ОК, и приложение будет запущено. Click the OK button and the application will run.
Рис. 04. диалоговое окно «Отладка не включена» (щелкните, чтобы просмотреть изображение с полным размером) Figure 04: Debugging Not Enabled dialog (Click to view full-size image)
При запуске приложения ASP.NET MVC Visual Studio запускает приложение в веб-браузере. When you run an ASP.NET MVC application, Visual Studio launches the application in your web browser. Пример приложения состоит только из двух страниц: страницы индекса и страницы About. The sample application consists of only two pages: the Index page and the About page. При первом запуске приложения отображается страница индекса (см. рис. 5). When the application first starts, the Index page appears (see Figure 5). Можно переходить на страницу About, щелкнув ссылку меню в правом верхнем углу приложения. You can navigate to the About page by clicking the menu link at the top right of the application.
Обратите внимание на URL-адреса в адресной строке браузера. Notice the URLs in the address bar of your browser. Например, если щелкнуть ссылку меню About, URL-адрес в адресной строке браузера изменится на /Хоме/абаут. For example, when you click the About menu link, the URL in the browser address bar changes to /Home/About.
Если закрыть окно браузера и вернуться в Visual Studio, вы не сможете найти файл с путем «Домашняя страница» или «о программе». If you close the browser window and return to Visual Studio, you won’t be able to find a file with the path Home/About. Файлы не существуют. The files don’t exist. Как это возможно? How is this possible?
URL-адрес не равен странице A URL Does Not Equal a Page
При создании традиционного приложения веб-форм ASP.NET или приложения Active Server Pages существует однозначное соответствие между URL-адресом и страницей. When you build a traditional ASP.NET Web Forms application or an Active Server Pages application, there is a one-to-one correspondence between a URL and a page. Если вы запрашиваете страницу с именем Сомепаже. aspx с сервера, то лучше быть страницей на диске с именем Сомепаже. aspx. If you request a page named SomePage.aspx from the server, then there had better be a page on disk named SomePage.aspx. Если файл Сомепаже. aspx не существует, возникает некрасивое сообщение об ошибке 404 — страница не найдена . If the SomePage.aspx file does not exist, you get an ugly 404 — Page Not Found error.
При создании приложения ASP.NET MVC, напротив, отсутствует соответствие между URL-адресом, введенным в адресную строку браузера, и файлами, найденными в приложении. When building an ASP.NET MVC application, in contrast, there is no correspondence between the URL that you type into your browser’s address bar and the files that you find in your application. В приложении ASP.NET MVC URL-адрес соответствует действию контроллера, а не странице на диске. In an ASP.NET MVC application, a URL corresponds to a controller action instead of a page on disk.
В традиционном приложении ASP.NET или ASP запросы к браузеру сопоставлены со страницами. In a traditional ASP.NET or ASP application, browser requests are mapped to pages. В приложении ASP.NET MVC, напротив, запросы браузера сопоставляются с действиями контроллера. In an ASP.NET MVC application, in contrast, browser requests are mapped to controller actions. Приложение веб-форм ASP.NET является ориентированным на содержимое. An ASP.NET Web Forms application is content-centric. Приложение ASP.NET MVC, напротив, является ориентированным на логику приложения. An ASP.NET MVC application, in contrast, is application logic centric.
Основные сведения о маршрутизации ASP.NET Understanding ASP.NET Routing
Запрос браузера сопоставляется с действием контроллера с помощью функции ASP.NET Framework, именуемой маршрутизацией ASP.NET. A browser request gets mapped to a controller action through a feature of the ASP.NET framework called ASP.NET Routing. ASP.NET Маршрутизация используется платформой ASP.NET MVC для маршрутизации входящих запросов к действиям контроллера. ASP.NET Routing is used by the ASP.NET MVC framework to route incoming requests to controller actions.
Маршрутизация ASP.NET использует таблицу маршрутов для обработки входящих запросов. ASP.NET Routing uses a route table to handle incoming requests. Эта таблица маршрутов создается при первом запуске веб-приложения. This route table is created when your web application first starts. Таблица маршрутов настроена в файле Global. asax. The route table is setup in the Global.asax file. Файл Global. asax MVC по умолчанию содержится в листинге 1. The default MVC Global.asax file is contained in Listing 1.
Листинг 1-Global. asax Listing 1 — Global.asax
При первом запуске приложения ASP.NET _ вызывается метод Start () приложения. When an ASP.NET application first starts, the Application_Start() method is called. В листинге 1 Этот метод вызывает метод Регистерраутес (), а метод Регистерраутес () создает таблицу маршрутов по умолчанию. In Listing 1, this method calls the RegisterRoutes() method and the RegisterRoutes() method creates the default route table.
Таблица маршрутов по умолчанию состоит из одного маршрута. The default route table consists of one route. Этот маршрут по умолчанию разбивает все входящие запросы на три сегмента (сегмент URL-адреса является любым символом обратной косой черты). This default route breaks all incoming requests into three segments (a URL segment is anything between forward slashes). Первый сегмент сопоставляется с именем контроллера, второй сегмент сопоставляется с именем действия, а последний сегмент сопоставляется с параметром, передаваемым в действие с именем ID. The first segment is mapped to a controller name, the second segment is mapped to an action name, and the final segment is mapped to a parameter passed to the action named Id.
Например, рассмотрим следующий URL-адрес: For example, consider the following URL:
Этот URL-адрес разбивается на три параметра следующим образом: This URL is parsed into three parameters like this:
Controller = продукт Controller = Product
Действие = сведения Action = Details
Маршрут по умолчанию, определенный в файле Global. asax, содержит значения по умолчанию для всех трех параметров. The Default route defined in the Global.asax file includes default values for all three parameters. Контроллером по умолчанию является Home, действием по умолчанию является index, а идентификатором по умолчанию является пустая строка. The default Controller is Home, the default Action is Index, and the default Id is an empty string. Учитывая эти значения по умолчанию, рассмотрим синтаксический анализ следующего URL-адреса: With these defaults in mind, consider how the following URL is parsed:
Этот URL-адрес разбивается на три параметра следующим образом: This URL is parsed into three parameters like this:
Контроллер = сотрудник Controller = Employee
Действие = индекс Action = Index
Наконец, если вы откроете приложение ASP.NET MVC без указания URL-адреса (например, http://localhost ), URL-адрес будет проанализирован следующим образом: Finally, if you open an ASP.NET MVC Application without supplying any URL (for example, http://localhost ) then the URL is parsed like this:
Контроллер = Главная Controller = Home
Действие = индекс Action = Index
Запрос направляется в действие index () в классе HomeController. The request is routed to the Index() action on the HomeController class.
Основные сведения об контроллерах Understanding Controllers
Контроллер отвечает за управление способом взаимодействия пользователя с приложением MVC. A controller is responsible for controlling the way that a user interacts with an MVC application. Контроллер содержит логику управления потоком для приложения ASP.NET MVC. A controller contains the flow control logic for an ASP.NET MVC application. Контроллер определяет ответ, отправляемый пользователю, когда пользователь выполняет запрос к браузеру. A controller determines what response to send back to a user when a user makes a browser request.
Контроллер — это просто класс (например, класс Visual Basic или C#). A controller is just a class (for example, a Visual Basic or C# class). Пример приложения ASP.NET MVC включает в себя контроллер с именем HomeController.cs, расположенный в папке Controllers. The sample ASP.NET MVC application includes a controller named HomeController.cs located in the Controllers folder. Содержимое файла HomeController.cs воспроизводится в листинге 2. The content of the HomeController.cs file is reproduced in Listing 2.
Листинг 2. HomeController.cs Listing 2 — HomeController.cs
Обратите внимание, что у HomeController есть два метода с именами index () и About (). Notice that the HomeController has two methods named Index() and About(). Эти два метода соответствуют двум действиям, предоставляемым контроллером. These two methods correspond to the two actions exposed by the controller. URL-адрес/Хоме/индекс вызывает метод HomeController. index (), а URL-адрес/Хоме/абаут вызывает метод HomeController. About (). The URL /Home/Index invokes the HomeController.Index() method and the URL /Home/About invokes the HomeController.About() method.
Любой открытый метод в контроллере предоставляется как действие контроллера. Any public method in a controller is exposed as a controller action. Необходимо соблюдать осторожность. You need to be careful about this. Это означает, что любой открытый метод, содержащийся в контроллере, может быть вызван любым пользователем, у которого есть доступ к Интернету, путем ввода правильного URL-адреса в браузере. This means that any public method contained in a controller can be invoked by anyone with access to the Internet by entering the right URL into a browser.
Основные сведения о представлениях Understanding Views
Два действия контроллера, предоставляемые классом HomeController, index () и About (), возвращают представление. The two controller actions exposed by the HomeController class, Index() and About(), both return a view. Представление содержит разметку HTML и содержимое, отправляемое в браузер. A view contains the HTML markup and content that is sent to the browser. Представление является эквивалентом страницы при работе с ASP.NET приложением MVC. A view is the equivalent of a page when working with an ASP.NET MVC application.
Необходимо создать представления в правильном расположении. You must create your views in the right location. Действие HomeController. index () возвращает представление, расположенное по следующему пути: The HomeController.Index() action returns a view located at the following path:
Действие HomeController. About () возвращает представление, расположенное по следующему пути: The HomeController.About() action returns a view located at the following path:
В общем случае, если требуется возвратить представление для действия контроллера, необходимо создать вложенную папку в папке Views с тем же именем, что и у контроллера. In general, if you want to return a view for a controller action, then you need to create a subfolder in the Views folder with the same name as your controller. Во вложенной папке необходимо создать файл. aspx с тем же именем, что и действие контроллера. Within the subfolder, you must create an .aspx file with the same name as the controller action.
Файл в листинге 3 содержит представление About. aspx. The file in Listing 3 contains the About.aspx view.
Листинг 3 — About. aspx Listing 3 — About.aspx
Если пропустить первую строку в листинге 3, большая часть представления состоит из стандартного кода HTML. If you ignore the first line in Listing 3, most of the rest of the view consists of standard HTML. Вы можете изменить содержимое представления, введя нужный HTML-код. You can modify the contents of the view by entering any HTML that you want here.
Представление очень похоже на страницу Active Server страниц или веб-форм ASP.NET. A view is very similar to a page in Active Server Pages or ASP.NET Web Forms. Представление может содержать HTML-содержимое и скрипты. A view can contain HTML content and scripts. Скрипты можно писать на любом языке программирования .NET (например, C# или Visual Basic .NET). You can write the scripts in your favorite .NET programming language (for example, C# or Visual Basic .NET). Скрипты используются для просмотра динамического содержимого, например данных базы данных. You use scripts to display dynamic content such as database data.
Основные сведения о моделях Understanding Models
Мы обсуждали контроллеры, и мы обсуждали представления. We have discussed controllers and we have discussed views. Последний раздел, который нам нужно обсудить, — модели. The last topic that we need to discuss is models. Что такое модель MVC? What is an MVC model?
Модель MVC содержит всю логику приложения, которая не содержится в представлении или контроллере. An MVC model contains all of your application logic that is not contained in a view or a controller. Модель должна содержать всю бизнес-логику приложения, логику проверки и логику доступа к базе данных. The model should contain all of your application business logic, validation logic, and database access logic. Например, если для доступа к базе данных используется Microsoft Entity Framework, то в папке Models (модели) необходимо создать классы Entity Framework (файл EDMX). For example, if you are using the Microsoft Entity Framework to access your database, then you would create your Entity Framework classes (your .edmx file) in the Models folder.
Представление должно содержать только логику, связанную с созданием пользовательского интерфейса. A view should contain only logic related to generating the user interface. Контроллер должен содержать только минимальную логику, необходимую для возврата правильного представления или перенаправить пользователя в другое действие (управление потоком). A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control). Все остальное должно содержаться в модели. Everything else should be contained in the model.
Как правило, необходимо стремиться к моделям FAT и фактам контроллерам. In general, you should strive for fat models and skinny controllers. Методы контроллера должны содержать всего несколько строк кода. Your controller methods should contain only a few lines of code. Если действие контроллера имеет слишком большой формат FAT, следует рассмотреть возможность перемещения логики в новый класс в папке Models. If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder.