The objective of ASP.Net MVC design pattern is separation of concern i.e. segregation of three building blocks of any application –
1. Model – comprises the business objects or the raw entities
2. View - the representation / interaction of the entities with the real world
3. Controller – the heart of any application where the business rules are defined and all operations are controlled.
The benefit that MVC 5 (shipped with Microsoft Visual Studio 2013) offers are the following:
Integrated ASP.Net – This is an excellent feature where developer does not need to decide whether to go for traditional web form based development or in MVC design pattern while choosing the project template itself.
Improvements in membership / authentication framework - There has been a lot of enhancements in memberships in this version of MVC; e.g. there are no distinction in terms of project types (be it ASP.Net web forms or others); it is considerably easy to customize or add new fields in the user registration area (just like any other controller); new types of authentication providers (e.g. Facebook, Twitter or Microsoft Azure providers) are supported for membership authentication.
Supporting of Bootstrap framework - Since MVC 5 supports Bootstrap framework which is widely accepted in other development platforms; it is much easier to incorporate diverse themes as per users wish.
Introducing code-first approach – By default MVC 5 offers code-first approach for database development increasing the flexibility and reducing time for change management.
Default structure for MVC applications
The basic steps to create an MVC application in Microsoft Visual Studio 2013 is shown below:
Step# 1
Step# 1 (Creating a new project in ASP.Net Web Application template)
Step# 2
Step# 2 (choosing MVC template and optionally choosing to add a Test project)
Step# 3
Step# 3 this is what this template provides us
The main folders in an MVC application (as displayed in the Solution Explorer) are as follows:
Controllers: This contains all the controllers that should be created in this application. By default this contains two classes called AccountController and ManageController. These are used for ASP.Net user / role management. Apart from these two the other class present here is HomeController which serves as the controller for default landing page.
Models: This contains all the models and ViewModels that will be created as part of the application. By default; this folder contains three model classes called IdentityModels, AccountViewModels and ManageViewModels and these are used for ASP.Net user management purpose only.
Views: This folder contains the views created in order to display them in browser or for operational purpose. Views are generally designed using Razor view engine which is default in MVC architecture.
One more thing needs a special attention here; that is the RouteConfig file that is present in App_Start folder. This file contains all the routes used by the application. Routing framework in MVC architecture plays a pivotal role in mapping the incoming requests to their intended Controllers and actions to be carried out. For example; in the picture below, if the request comes for “Default” page through the URL it will be mapped to be handled by HomeController and the method called “Index” will be used to render the view to the browser.
Step# 4
Step# 4 App_Start\RouteConfig contains all the routes for the application
Model
In the picture below new models are being added to the project:
Step# 5
Step# 5 Adding a new model (ItemModel) in the sample project
Below are the two models created in the “Models” folder:
Step# 6
Step# 6 Structure for the DepartmentModel model
So, it is evident from the structure that ItemModel makes use of DepartmentModel as one of its properties. Now let’s try creating the Controller for the ItemModel. By right-clicking on Controllers folder choose Add > Controller… to add a controller.
Step# 7
Step 7 Structure of the ItemModel model
Step# 8
Step#8 Adding ItemController to the application
Step# 9
Step# 9 Choosing scaffolding
Note: scaffolding option – scaffolding is nothing but an important option in MVC to generate the boilerplate code for a basic CRUD (Create Read Update Delete) functionality for the models in the application. Also it can be noted here that there are multiple possible options for scaffolding templates to choose from. We have chosen the option “MVC 5 Controller with views, using Entity Framework” as this is a easiest option to follow for the time being. If anyone wishes to write the controller classes completely by hand; he/she is absolutely free to ignore scaffolding.
As soon as the scaffolding option is chosen; the next dialog comes up for choosing the model based on which the Controller and views will be generated as shown below:
Step# 10
Step# 10 Choosing ItemModel to generate Controller and views
Step# 11
Even after the Model has been chosen the “Add” button stays disabled. Because a DataContext class has to be chosen to proceed. This DataContext class is responsible for managing the database structure for the model for which controller is being created. As no DataContext class has been created for this it is needed to hit the ‘+’ button to generate one.
Step# 11 Choosing DataContext class
At this point, if we try to build the DataContext Visual Studio throws an error as shown below:
Step# 12
Step# 12 Visual Studio error displayed if no property is defined as ‘Key’
Step# 13
So we made a simple change in ItemModes class (shown in Step 13) and rebuilt the project. Now the controller is generated.
Step# 13 Added Key attribute for ItemId property in ItemModeltest
Fluent API
At this stage; let’s have a look at where Fluent API comes into picture in MVC architecture design pattern. The screenshot shown below shows the DataContext class generated in the process of creating the Controller class using scaffolding template.
Step# 14
Step# 14 Bare-bone structure of the DataContext class createdtest
Step# 15
Step# 15 Web.config entry for the connectionString
This implies the following two points:
Whenever the application will run & if nothing is changed in both the Web.config and DataContext class; then a database with the name mentioned in Initial Catalog parameter in Web.config will get created in local db;
If we want our own database to be created and used by our application we will need to change the Web.Config connectionString entry accordingly and assign the same name in constructor of the DataContext class (i.e. MVCAppContext).
Step# 16
Step# 16 Overriding OnModelCreating method of DbContext class if needed
Once the application is run; the following objects get created in local db (as specified in Web.Config). We can see them in Server Explorer view.
Step# 17
Step# 17 Verifying the tables related to Models get created
Views
The default view Index.vbhtml created by scaffolding template looks like:
Step# 18
Step# 18 Default Index.vbhtml created by scaffolding
Step# 19
And the corresponding view in browser looks like:
Step# 19 Index.vbhtml viewed in browser
Step# 20
The Create.vbhtml looks like as shown below:
Step# 20 Create.vbhtml shown in browser
Step# 21
The validation messages are appearing as the corresponding validations have been provided in the ItemModel as shown below:
Step# 21 Validation for ‘Required’ field added in ItemModel for those fields
Step# 22
As we created an item; it is being displayed in Index page as shown below.
Step# 22 Display of recently added item
Step# 23
Controllers
In this section, controllers are going to be discussed. The ItemModelController class created by scaffolding framework has been shown below
Step# 23 Controller class generated by scaffolding
Important Note: Corresponding to each possible action to be performed on the model; a function has been defined (Create, Details, Index, Edit and Delete). The common to all of them is that they return View as the return type. Now it is mandatory that we have each corresponding view defined for each of these functions.
Conclusion
MVC design pattern is an evolving design methodology in Microsoft .Net development paradigm. The main essence of this architecture is clear separation of concern and effortless ease with which Razor views can be tweaked based on diverse requirement. Data annotations are very useful when it comes to make the code structure easy to read and debug apart from incorporating validation rules.
The post An Introduction to ASP.Net MVC – Working Code Sample appeared first on CodingThis.com.