Creating application using ASP.Net MVC 5 with Visual Studio 2013 (Code First Approach)
In this article we will see the new features of Visual Studio 2013 in terms of ASP.Net MVC 5. We will also see the new templates for the ASP.Net MVC and will walk-through by creating a new application in ASP.Net MVC 5 using Visual Studio 2013. We will see each and every steps which needs to create the application in ASP.Net MVC 5 in Visual Studio 2013.Here I am using the Code First Approach in which the database will be created automatically using the Model classes.
Hey Friends,
In this article we will see the new features of Visual Studio 2013 in terms of ASP.Net MVC 5. We will also see the new templates for the ASP.Net MVC and will walk-through by creating a new application in ASP.Net MVC 5 using Visual Studio 2013.
1. To Start with the ASP.Net MVC 5 with Visual Studio 2013, first we need to install the Visual Studio 2013. To install the Visual Studio 2013 free for 3 months, you can go through the below link to download:
http://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx
2. Once you will install the Visual Studio 2013 Express edition, you should be able to see the new green icon for the Visual Studio 2013 as below:
3. Click on the Visual Studio 2013 and Go to the File --> New Project
4. Move to the Web section, you will see that there is only one template for the Web Development. This is called as ASP.Net One (new feature of Visual Studio 2013). So from Visual Studio 2013, the Microsoft has provided the one template for all the web application development. Enter the project name and click OK.
5. Another template window opened with the options to create the Web application.
6. Lot of new things we can see in this window. There are the templates available for different types of web application development.
• Empty - This project template provides an Empty Solution application. We can make any type of application by using this template.
• Web Forms- This template can be used to build the traditional ASP.Net Applications.
• MVC – This template is exclusively to create the ASP.Net MVC related applications
• Web API- This application template is to create the Web API applications.
• Single Page Application- This template is to create SPA type of applications.
With all this information we can also see other details like:
Add Folders and Core References For: -• Web Forms, MVC and Web API. These check-boxes are used to add the references and required nugget packages to the application which you are going to develop.
Another option you will see here Change Authentication button. This button is used to change the authentication type of the application. The default authentication is Individual User Accounts.
We can change the authentication type by clicking on the button. When you click on the button, you will see the below screen and by choosing the radio button, we can change the authentication type and then we can configure the authentication as required.
After choosing the configuration, click OK.
We can also see the option to host the website to Windows Azure environment.
Click OK.
7. Once you click OK, it will take some time to get all the Nudget packages for the Website and required configuration to be included.
8. Once all the processing is done, you will be able to see the below page with the solution explorer:
So this is the new Home Page for ASP.Net MVC 5 application.
Just run the application and check if all the things are fine.
You can also check that each of the links which are provided in default, are working fine.
9. Now we will go through each of the folder in the solution and will see all the files in the folders and their work, one by one:
1. App_Data folder- This folder is to keep the database or related stuff.
2. App_Start folder- This is the folder which is used to keep the files which are related to reading the configuration related to route, bundles, startup page etc
a. BundleConfig.cs- This file contains the details to include the JavaScript files (.js files), styles (.css file) which are used in the website. If we want to provide our own scripts or css styles, we can include using this file. We need to add the reference of these files as below:
Here you can see that I have included JavaScript file with the name myJSFile.js and a style mySite.css.
b. FilterConfig.cs-By using this file, we can register global filters. This feature got included since ASP.net MVC 3 version. If we want to implement throttling, we can make use of this file to set the number of requests per second and/or time of request expiration etc.
c. IdentityConfig.cs-To configure the role providers and membership providers, we can make sue of this file.
d. RouteConfig.cs- This file is most important file as the whole ASP.net MVC depends on this file. This file is used to provide the route for the requests. This file contains the routes which validates the incoming requests. If the request is valid, the request will be further processed else it will be rejected. All the requests which are made to the ASP.net MVC application should be validated by the route using this file.
Here we can also see that they have provided a default route. We will try to understand that default route first:
The RegisterRoutes method is used to register as many routes for the website. We can map our own route here by using the MapRoute method.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
The first line describes that the request should ignore the routes which are ended with .axd. We can also define other routes to ignore as these are not valid files in request URL.
The default route consists of the URL, which is having the pattern like controller/action/id
It means the requests which are validated with this pattern, will be accepted and will be processed further.
Also in the next line we can see the default which shows that if the pattern is not followed then it will take the Home as the default controller name and the Index as the default action and id is not mandatory.
So if our website is not having the pattern in the URL then there must be a Controller name called as Home and it should have the Index method and obviously it should have the corresponding View and then we can see the default page.
If you closely observe our URL which we run as default is not having the controller name or action name in the URL, it means it is taking the default values for those attributes.
Now instead of Home page, I want my Login page should come as the first like default page in ASP.Net. Here we don't have any option to set the default page by the solution files. To make any page as default page, we need to create a route where if we don't provide anything in URL, it should take my page as default page:
Here you can see that we have created another route which we are mapping to the Login page and providing the default controller name as Account and Action name as Login. we have not written anything in the URL. So now if we won't provide any URL, it will take the Login page as our first page as seen below:
So by this way, we can make any page (View) as our first page in ASP.Net MVC application.
e. Startup.Auth.cs- This file is related to startup authentication. This file specially included for the external authentication plugins like social website logins e.g. Google, Facebook, and Twitter etc. We can enable those authentications using this file by configuring few items. By default it uses Cookie based authentication.
3. Content folder- This folder contains the css style files. And we can see here that the css for the Bootstrap template is already added by default (new feature in ASP.Net MVC 5.
4. Controllers folder- This folder is to include all the controller files of the application.
We can add as many controllers under the folder. The default controllers are listed here.
5. Fonts folder- This folder contains the fonts formats which are used in the Bootstrap files.
6. Models folder- This folder contains the models for the application. Models are the container to carry the data. So we can have all the model files under this folder.
The default model files are included.
7. Scripts folder- This folder contains all the script files (JavaScript libraries) which are used in the application.
Here we can see two types of file. Most of the files are duplicates with min files. Actually the min files are similar to without min file but they are written in a single line without spaces. These min files are used when we want to deploy our application, we deploy with only the min files as they will take less bandwidth when downloading to the browser to run the application. For the first time, when the browser tries to open the file, it first downloads all the client files and then applies all the styles and opens the first page.
As the MVC applications are using many client files in development, so to use the less bandwidth, they use min files so the content will less as compare to without min file. If we want to modify or debug the files, we use those files which are without min as they are more readable. But in deployment, we deploy the min files.
8. Views folder- This folder is used to keep all the views (UI related files) used in the application.
Also we can see here that for a controller, there is a folder with the same name in the Views section. So each view folder contains the view files which are related to the corresponding controller. This is not mandatory. It is default design and structure of the ASP.net which the Microsoft has provided.
With that we can see an additional folder name called Shared. This folder is exclusively for the shared Views like if we want some common Views e.g. like Master page, Error page
We will try to see the various files under the Shared folder.
Shared folder- This folder consists of 3 Views by default.
_Layout.cshtml- This file is the master page for the application.
Here we can see that the _Layout.cshtml contains all the links which we can see in all the pages also the Title and in the last line, there is a method called as RenderBody(). This method is used to render the body of the content views. The views which get loaded in to this master page used this method.
_LoginPartial.cshtml- This is a partial view which is part of the View and is under the same Shared folder. When the authentication fails, this view gets called so they kept this view under the Shared folder.
Error.cshtml- Any error which will displayed under by using this view. So this is the common error page to display all type of errors in the website. We can also design or modify this view to show our errors.
Lockout.cshtml-to show whether the account is locked out based on some time duration. We can display this page through the application when the user account is locked out.
_ViewStart.cshtml- This is the common view which is used to keep the master page URL. By default, this page contains the URL of the _Layout.cshtml
If we want our own master page multiple master pages, we can define the current master page URL in the view.
9. Global.asax- This is the file similar to the ASP.Net but having only one default method Application_Start.
It is having the method to register all the startup files which are inside the App_Start folder.
We are familiar with other files methods except
AreaRegistration.RegisterAllAreas();
This method is used for the area registration. Areas are also one of the separation by which we can have the all MVC component based on the modules. Let's say the Admin module can have an Area which contains Model, View and Controller, the User module can have another area with their corresponding Models, Views and Controller. Also each are will have a file which contains the route based on that area.
Startup.cs file- This file contains the reference of Startup.Auth.cs and calls its method to do the authentication first.
Now as we completed the initial introduction of each of the files in the solution and walk-through of the installation of Visual Studio 2013 with ASP.Net MVC 5, we will create a small application and see the working of its components.Creating an application in ASP.Net MVC 5 using Visual Studio 2013 with Code First Approach
As we have our solution ready for now with the default templates. So we will proceed with our existing solution.
1. As our application name is "SchoolManagementDemoMVC5", so first we will try to change our Master page so that our main menus should be according to our application.
We will add the Following menus in to the master page:
Admin Master- Admin login, Add Admin Details, Edit Admin Details, Delete Admin Details
Student info- Students, Add Student, Delete Student, View Student, Edit Student
Course info- Courses, Add Course, edit Course, Delete Course
Documents- Documents, Add/Upload documents, delete Documents, Edit Document
Based on these modules, we will modify our _Layout.cshtml file, the tile and other Links.
2. After modifying the _Layout.cshtml file, we should be able to see the below main page
As we can see that I have modified the content under the Getting started and under the More... sections.
3. Now we will add few Model classes for the Student and Course as below:
To add a new Model class, Right click on Models folder, Add --> Class
Provide the name of the class and add few public properties with getter and setter. There is no naming convention for the Model classes.
I just added StudentModel and CourseModel classes with few properties. I also created an additional class Student_Course which will map the student with the Courses they opt for. This class will work as the ViewModel for the Student and Course. Include the Student and Course classes inside the ViewModel.
There are 2 approaches; we can work with the database-
1. Code First Approach
2. Database First Approach
First we will see Code First Approach. In this approach the database will be created based on the Code (model classes). We will use the Model classes to create the database tables and then we will use the same database in our application.
Code First Approach
To work with the Code First approach,
1. We need to create a Context Class (entity Framework) which will be used for the database purpose. For now, we have created an additional class with the name SchoolContext and inherit it with the DbContext.
We need to define those classes in DbContext class for which we want to enable the CRUD operations. So we are defining here Student and Course classes in our DbContext class named as SchoolContext. These classes will be used for the CRUD operations.
2. Now as we have our DataContext class, it means we need to define the connection in our Web.Config file.
Go to Web.Config file of the root directory and the add a new connection with providing the same name as our DataContext class- SchoolContext
Here I just added the name as Student.mdf for our Database.
3. Now we will create controllers and then add the CRUD functionality for those model classes by providing our DataContext class. This step can be done in two ways-
a. Write the code by adding the empty controller
b. Generate all the code using Scaffolding option
We will go with the option 'b' and will see that how all the Views; Controller gets generated automatically with all the code written by Visual Studio.
4. To generate the Controller, Right click on the Controllers folder and Add --> Controller
We will see the Scaffolding options in the below window:
We are choosing the 3rd option "MVC 5 Controller with Vies using Entity Framework". This option will generate all the Controller methods, Views for our CRUD operations.
After choosing the 3rd option, click Add. Now it will ask you to provide the name of the model class and the data context class. So we will add here as below:
After providing all the required fields, click on Add button. Now the Visual Studio will take some time to generate all the Scaffolding options in the Controller and generating all the Views in the Views folder for this controller.
5. So you will see the below screen for a while to get all the files automatically added in to our structure.
6. Once all the processing is done, if you see the student controller will have all the CRUD operations methods:
7. Also you can see a new folder got created under the Views folder and have all the views generated automatically.
8. Now we can just run our project and click on Student info to see whether it's working or not. Just build the project and press Ctrl + F5(Run without debugging)
9. So as we can see the student records which were in our initializer class are populated with the List view. We can also check the other functions Edit, update, delete and all will be working as expected.
10. In the same way, we will create for the Course. Create CourseController by using the same Scaffolding options as below:
After entering the valid values, click on the Add button to generate the CRUD operations in the controller and corresponding views.
11. We can see for the Courses, we got the similar structure as well:
The CourseController.cs class:
And the corresponding Views structure:
12. We can run the project again to check whether we can see the entire course which we had in the initializer class. We can perform the CRUD operations on this data and can see the data in the table.
13. Till now we have not seen that where the database got created. Just go to the App_Data folder.
When you expand the App_Data folder, you should be able to see your database file as we mentioned in the Web.Config file,School.mdf
Right click on this file and click on 'Include In Project'
The file will get included in to project.
Double click to open it and you can see our tables got created.
To check the table data, right click and show table data. We can see the definition of the table as well.
Can you observe clearly, that we didn't enter any Id but by default the id has assigned and it is auto generated and incremented by 1.
This happens when we have the (class name + id) as the property name.
With the same way, we can do for the other tabs.
Hope this article will be helpful for those who are looking out for ASP.Net MVC 5 and the new features in Visual Studio 2013 in terms of new templates.
Hi Pawan really helpful thanks for sharing.