First Application in ASP.NET MVC 5

By | November 3, 2014

So we will now create our first application in ASP.NET MVC. Step by step instructions are given below:

->. Open Visual Studio 2013

->. Click File->New -> Project as follows

01_FirstApp

-> After clicking “New Project” dialog box will appear to user:

-> In New Project dialog box

1). First confirm the .Net Framework set to 4.5.1

2). Select Visual C# Option -> Web ->ASP.NET Web Application

3). Enter the name of the project as “MyFirstMvcApp”

4). Browse and set the location of the Project

5). Click OK Button as follows:

02_FirstApp

Note: We selected .NET Framework version 4.5.1 because the latest version of .NET is required for some of the advanced features that we will describe later.

->. Now another dialog box will appear to user that will ask user to set the initial content for ASP.NET Project as follows:

25_ASPNETMVC

->. Inside above dialog box we will find following sections:

1). Select a template

2). Add folders and core reference for

3). Add unit tests

4). Configure Authentication

5). Windows Azure

->. Now we will shortly discuss about above sections:

1). Select a template

>>. In this section we will find some application templates as follows:

Template Name Description
Empty >>. Empty template sets you up with an empty project skeleton.>>. In this project we will get web.config with some default website configuration and few assembly references that need to get started>>. There is no code, no JavaScript, no CSS, even no static HTML file.>>.  We will not be able to run the empty project until put something in it.>>. By using empty project template we will be able to create a project from scratch.
Web Forms >>. This template sets you up for ASP.NET Web Forms development
MVC >>. This template sets up for ASP.NET MVC web development.>>. This template starts with a standard home controller with a few views, configures the site layout, and includes an MVC-specific Project_Readme.html page.
Web API >>. Use for create RESTful HTTP services that can reach wide range of clients including browsers and mobile devices.
Single Page Application >>.  Use for create rich client side JavaScript driven HTML 5 applications using ASP.NET Web API.>>. This template use Knockout.js library to help manage interactions in the browser.
Azure Mobile Service >>. Project template for creating ASP.NET Web API based mobile backend for Microsoft Azure Mobile Services

2). Add folders and core reference for

>>. This section contains three check boxes as follows:

Name Description
Web Forms If we wish to add folders and references of Web Forms to our application then check it.
MVC If we wish to add folders and references of MVC to our application then check it.
Web API If we wish to add folders and references of Web API to our application then check it.

3). Add unit tests

>>. Allow unit test project with sample unit tests.

>>. All the built-in project templates have an option to create unit test project.

4). Change Authentication

>>. This is a Button

>>. If we click this Button there will be another dialog box will appear to us as follows:

26_ASPNETMVC

>>. Above dialog box contains four Radio Buttons

Name Description
No Authentication >>. Used for an application that requires no authentication, such as a public website with no administration section.
Individual User Accounts >>. Used for applications that store user profiles locally, such as in a SQL Server database.>>. This includes support for username / password accounts as well as social authentication providers.
Organizational Accounts >>. Used for accounts that authenticate via some form of Active Directory (including Azure Active Directory and Office 365).
Windows Authentication >>. Used for intranet applications

Note: In current application we’ll use Individual User Accounts so we’ll select this Radio Button.

5). Windows Azure

>>. Visual Studio 2013.2 adds an additional “Host in the cloud” option to configure Azure resources for a Project.

>>. If we want to use host our application in cloud then check this check box otherwise uncheck the checkbox.

->. In this dialog box we will

1). Select “Empty” template

2). Check MVC check box in “Add folders and references” section

3). Click OK Button as follows:

03_FirstApp

Note: We will create a basic MVC project with minimal predefined so we selected “Empty” here.

->.Now Visual Studio created a Project with a number of files and folders that will be shown at “Solution Explorer” as follows:

04_FirstApp

-> Now we will introduce the core directories of our “Solution Explorer”

Directory Description
/App_Data >>. Inside this directory store data files for read/write data inside it>>. IIS will not serve the contents of this folder.
/App_Start Inside this directory put configuration code for features like Routing, bundling, and Web API
/Controllers >>. Inside this directory put all Controller classes that handle URL requests>>. This is a convention.>>. One can put controller classes anywhere he/she like, because they are all compiled into the same assembly.
/Models >>. Inside this directory put all classes that represent and manipulate data and business objects>>. This is a convention.>.. One can define your model classes anywhere in the project even in a separate project.
/Views >>. Inside this directory put UI template files that are responsible for rendering output, such as HTML.>>.The /Views/web.config file prevents IIS from serving the content of these directories.>>. Views must be rendered through an action method.
/Views/web.config >>. This is not the application configuration file.>>. It contains the configuration that required to make views work with ASP.NET>>. Prevents serving views from directory because contents of view directory will be rendered through action methods.
/Global.asax >>. Global ASP.NET application class.>>. It has a code behind class named Global.asax.cs.>>. In ASP.NET MVC register routing configuration place here.>>. If any code needs to run during application initialization or shutdown the application also place here.
Packages.config >>. This file is managed by the NuGet infrastructure.>>. It’s used to track installed packages with their respective versions.
/web.config This is the configuration file for your application

In a complete ASP.NET MVC project there can be several more directories as well as with previous directories as follows:

Directory Description
/Areas Way of partitioning a large application into smaller pieces.
/bin >>. The compiled assembly for MVC application is placed here, along with any referenced assemblies that are not in the GAC.>>. One won’t see the bin directory in the Solution Explorer window unless click the Show All Files button.>>Since these are binary files generated on compilation, you should not normally store them in source control.
/Content >>. Inside this directory put CSS, images and other site contents else scripts.>>. This is a convention but not required.>>. You can put your static content anywhere that suits you.
/fonts The Bootstrap template system includes some custom web fonts, which are placed in this directory
/Scripts >>. Inside this directory put all JavaScript libraries i.e. .js files>>. This is a convention.>>. You can put script files in any location, as they are just another type of static content.
/Views/Shared This directory holds layouts and views which are not specific to a single controller.

->.Now run the application from

1). Debug-> Start Debugging as follows:

05_FirstApp

2). Or Press F5 key

3).Or by Click Debugging as follows:

06_FirstApp

->.Though we run an Empty project so the application doesn’t contain anything to run so the server generates a 404 i.e. Not Found Error as follows:

07_FirstApp

->. Stop Debugging.

->. Now we will add a Controller class in our project.

->. What is Controller?

–>. Controllers are C# class

–>.Each Controller class is inherited from “System.Web.Mvc.Controller” i.e. Controller.cs class

–>.Controller class inherited from BaseController.cs class

–>. Inside a Controller class each public method is called Action Method.

–>. Each ASP.NET MVC Project contains a folder named Controllers as shown below:

08_FirstApp

–>. All Controller classes should define inside that folder.

         Note: It’s a convention not mandatory. You can put your controller classes anywhere you like, because they are all compiled into the same assembly.

->. Now let’s add a new Controller.

->. First Right Mouse Click on Controllers folder of our Solution Explorer-> Add-> Controller as follows:

09_FirstApp

->.A dialog box will appear to us

->. From Left Pane Select Common-> MVC.

->. So List of MVC Controller Scaffolding templates will seen as follows:

.16_ASPNetMVC

->. Now we will shortly introduce above three templates:

 1). MVC 5 Controller – Empty:

=>. This controller contains only Index action method with no code inside the action method.

=>. This template will not create any views.

=>. If the action methods return type change to ViewResult then views can be created by this template.

2). MVC 5 Controller with read/write actions

=>. This controller will contain all read/write actions i.e. Index, Details, Create, Edit and Delete actions.

=>. The action methods are not entirely empty but they won’t perform any useful work until we add our own code and create the views for each action.

3). MVC 5 Controller with views, using Entity Framework

=>. This template controller with entire suite of read/write actions i.e. Index, Details, Create, Edit and Delete.

=>.Also generates all the required views and the code to persist and retrieve data from database.

 Note: Above all three Controllers are derived from Controller.cs class and Controller.cs class derived from ControllerBase.cs class.

->. From that dialog Select

1). “MVC5 Controller-Empty”

2). Click “Add” Button as follows:

15_AspNetMVC

->.So “Add Controller” dialog will appear.

->. Inside that dialog

1). Set the name to “HomeController”

2). Click “Add” Button as follows:

11_FirstApp

Note:

#. Each Controller name must have Suffix “Controller”

#. “HomeController” is default controller.

->. So a new controller will created that’s name “HomeController.cs”

->. Inside that Controller there has a single Action Method named Index as follows:

12_FirstApp

->.Now we will modify our Controller as follows:

13_FirstApp

->.In above code we changed the method return type from “ActionResult” to “string” and instead of return “View()” we returned string “Hello, This is our first Controller.”

->. Run the application. In browser our output as follows:

14_FirstApp

->. Above example isn’t HTML, it was just the string “Hello, This is our first Controller”.

->. To produce HTML response for a browser request we need a View

->.So now we will work with View

->. First we will Change Action method of Controller i.e. HomeController.cs as follows:

17_ASPNETMVC

Note: By returning “ViewResult” actually instruct MVC to render a View.

->.Now we run our project. It will show following error message in browser

18_ASPNETMVC

->.Above error message tells us

=>. MVC did not find any view for this action method

=> List of locations where MVC looked for view.

->. In above error message we see that in all the locations MVC looked for Index.aspx / Index.ascx / Index.cshtml / Index.vbhtml

->.Why MVC looked only for Index named view?

->.Because of the convention of MVC “Views are always associated with action methods by their naming” i.e. according to MVC convention “Action Method name and View Name must be similar”.

->. So for Index method View name must be Index.

->. Some important points to be noted:

=>. All views are placed inside “Views” folder of Solution Explorer.

=>. Inside “Views” folder views are placed inside different folders.

=>.According to MVC convention “Name of those folders are similar to Controller name”.

=>. So views of “HomeController” will placed inside Home named folder i.e. Views/Home location of Solution Explorer.

->.Now we will create our first view.

->. Right mouse click anywhere of Action Method -> Add View as follows:

19_ASPNETMVC

->. So new dialog box will appear to us named “Add View” as follows:

20_ASPNETMVC

->. Inside that dialog box

1). View name:

#. Here we will enter the name of View e.g. Index, List, Edit, Save, Delete.

#. Name of the View must be same with Action Method name of Controller e.g. Index action method’s view name will be “Index”

2). Template: Drop down list that will contain different scaffolding template name for creating different views. In ASP.NET MVC5 following types of scaffolding templates are available for creating view:

View Name Description
Create Scaffold Create/Insert screen/view for a Model e.g. Create Screen for Person Model.
Edit Scaffold Edit/Update screen/view for a Model e.g. Edit Screen for Person Model.
Delete Scaffold Delete screen/view for a Model e.g. Delete screen for Person Model
Details Scaffold Details screen/view for a Model against certain contagion e.g. finds the person details by their id and show the details in this view.
List Scaffold List screen/view for a Model e.g. list of all persons that already exists in database.
Empty Scaffold an Empty view. During Creating the view Model class need to select
Empty (without model) Scaffold an Empty view also no model will specify for this view.

 3).Model Class: Drop down list that will contain all the model classes of this project. Developer will select required model for specific view from this drop down list e.g. Person model class for persons “List” view

 4).Options: This section contains three options as follows;

4.1). Create as a partial view: If we define the view as partial view then we will select this option

4.2). Reference Script Libraries: Reference script libraries checkbox when scaffold a new view

4.3). Use Layout Page: Refer the Layout page i.e. _Layout.cshtml when scaffold a new view

->. Now we will set

1). View name: Index i.e. our  view name will be Index

2).Template: Empty(without model) i.e. our view will be empty and we will not select any model class for this view

3).Model: disabled because we will not select any model class for this view

4).Create Partial View: Uncheck this option because we will not create this view as partial view

5)..Reference Script Libraries: Will disabled

6). Use Layout Page: Uncheck this option because we will not use any Layout for this page i.e. our Layout will be empty.

7). Then Click Add Button.

21_ASPNETMVC

->.So new Index.cshtml View will create with following definition

@{

Layout = null;

}

 

<!DOCTYPE html>

 

<html>

<head>

<meta name=”viewport” content=”width=device-width” />

<title>Index</title>

</head>

<body>

<div>

</div>

</body>

</html>

->. Now if we check Views folder of Solution Explorer we will find that a new folder created inside this folder with named “Home”. Inside that folder we will find Index.cshtml file as follows:

22_ASPNETMVC

->. Inside above Index.cshtml files maximum code is HTML.

->. Only exception is

@{

Layout = null;

}

->.Razor view engine will interpret this expression, processes the contents of views, generates HTML and sent to the browser

->. Layout = null means that no layout use in this view.

->.Now we will add a line of code inside <div></div> of <body></body> Index.cshtml as follows:

<body>

<div>

“Hello, this is our first view”

</div>

</body>

->. Then Run the program. It will return us following output

23_ASPNETMVC

->. Now Index method returns a ViewResult so the MVC Framework renders a view and returns the HTML that it produced.

->. In this case we didn’t tell MVC which view should be used

->. So it finds the view automatically by using the naming convention.

->.The convention is

1).  The view name is same to the Controller Action method name i.e. our controller’s action method name is “Index” also our view name is “Index”

2). The view placed inside the folder that’s name is exactly same as controller name i.e. our controller name is Home also our cshtml view container folder name is Home.

24_ASPNETMVC

1955 Total Views 2 Views Today
Md. Mojammel Haque

CSM, CSPO, CSD, CSP-SM, CSP-PO (ScrumAlliance.org)
Certification Profile Link-
https://www.scrumalliance.org/community/profile/mhaque13

Currently working as Lead Team (Application Architecture) at Raven Systems Ltd. Passion for software development especially agile practices such as TDD with in depth knowledge of Object Oriented Programming, SOLID Principles, Gang of Four Design Patterns, Some Enterprise Application Architectural Patterns. Over 8 years of software development experience ASP.NET. Has the ability to understand and transform complex business requirements into software ensuring applications are delivered on time. Also experience in non Microsoft .NET technologies such as Dapper.Net, Git, Structure Map & Angular, Bootstrap, HTML-5, CSS-3 etc.

Category: Asp.net MVC Tags: , ,
Md. Mojammel Haque

About Md. Mojammel Haque

CSM, CSPO, CSD, CSP-SM, CSP-PO (ScrumAlliance.org) Certification Profile Link- https://www.scrumalliance.org/community/profile/mhaque13 Currently working as Lead Team (Application Architecture) at Raven Systems Ltd. Passion for software development especially agile practices such as TDD with in depth knowledge of Object Oriented Programming, SOLID Principles, Gang of Four Design Patterns, Some Enterprise Application Architectural Patterns. Over 8 years of software development experience ASP.NET. Has the ability to understand and transform complex business requirements into software ensuring applications are delivered on time. Also experience in non Microsoft .NET technologies such as Dapper.Net, Git, Structure Map & Angular, Bootstrap, HTML-5, CSS-3 etc.

10 thoughts on “First Application in ASP.NET MVC 5

  1. moshiur abir

    This very helpful tutorial. i just like it.carry on and go ahead

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *