Professional Documents
Culture Documents
265
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
articles
Q&A
Sign in
forums
lounge
Searchforarticles,questions,tips
CPOL
Rate this:
4.85 53 votes
Introduction to ASP .NET MVC 5 for .NET developers that are completely new to Web development, MVC frameworks and Web
Application Frameworks in general.
Introduction
This tutorial is aimed at .NET developers that are total beginners in the Web Applications world and want to get started using
familiar Microsoft .NET technologies.
Prerequisites
HTML basic skills structure of a web page, tags
CSS basic skills, including basic familiarity with the Bootstrap framework
C# you should be fully comfortable writing C# applications, and be familiar with the following features:
LINQ
Anonymous Types
Expressions
.NET Framework libraries you should be familiar with popular framework features, such as:
Entity Framework Code First basic
Dynamic variables
Development Environment
In this tutorial I will be using Visual Studio 2013 Ultimate edition for all demonstrations. You may use any edition of Visual
Studio 2012 and upwards. There is a free Express version available be sure to download the Visual Studio Express for Web
edition.
If you are not using Visual Studio 2013, you will only be able to create MVC 4 items unless you install the ASP.NET and Web
Tools 2013.1 for Visual Studio 2012 package, whereas the examples will be based on ASP .NET MVC 5. Thats okay
though, as the differences between the versions are mainly in authentication features and not in syntax.
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
1/22
1443031750859.335
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
What is MVC?
MVC is not a Microsoft technology. It stands for Model View Controller. It is a common design pattern that exists in many Web
Application frameworks such as Ruby on Rails, Django and Zend Framework. MVC is commonly used to structure useroriented
applications meaning applications that have a Graphical User Interface GUI.
MVC is somewhat similar to MVVM Model View ViewModel if you come from the WPF world, but we will not be delving into
the differences between these in this tutorial.
Model
A model is a plain vanilla class that represents the structure of your data that you want to make visible to the user. A typical
Model class would only include dumb, public properties. For example, for the Person model you would include the following
properties:
Name
Address
Email
Phone
Other components of MVC will use the Model classes to perform logic for example, add a Person to a database and to display
it to a user render an HTML page displaying data about John Smith.
Its important to realize that this Model is intended for the View, and not necessarily for the entire application. It is perfectly
normal to have a Person Model class that is used internally in your application, in the server side for example, processing credit
card details for a Person, and then have a Person Model class in the MVC project. This is called a View Model.
View
A View is the result that the user will see when interacting with our Web Application. This is typically an HTML page, but it can
also be raw data represented by XML or JSON, or binary data for example, a .zip file.
Views are created dynamically by the Web Application Framework when the request is performed by the user, and are not
stored on the server beyond caching mechanisms that are implemented internally.
Controller
A Controller is a class which performs the linkage between the View and the Model. For example, if a user requests a list of all
the Persons in our application, the controller class will contain the code which accesses the database, queries it for the
appropriate user set, and then creates a View with the given Model which would be a list of the Persons returned from the
database.
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
2/22
1443031751139.137
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
Each controller exposes a set of public methods, called Actions. This is your applications API. Each View is associated with a
single controller, but a controller may have multiple Actions that return different Views.
Putting your business logic into the Controller class is bad practice. The Controller should only be responsible for retrieving data
& processing it, while the business logic itself should be delegated to the appropriate classes and interfaces that may not even
necessarily be a part of the MVC Web Application.
Routing
Routing is the process responsible for resolving, or routing a URL into a specific Action in a specific Controller. For example, if
our imaginary Person application is hosted at http://www.mypersonmanager.com, and we want to call the GetPersons Action,
which is a method in the Person controller class, our route will typically look something like
http://www.mypersonmanager.com/person/getpersons.
Routing is also used to pass parameters for Actions. For example, if we have a GetSpecificPerson Action which accepts an Id
parameter and we want to call it with the Id being 6, we will typically pass a parameter to it in the following syntax:
http://www.mypersonmanager.com/person/getspecificperson/6.
Note that the syntax presented here is a generic example, and while most Web Application Frameworks generally follow these
conventions, there might be differences between them.
3/22
1443031751357.763
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
Our first application will be very simple: it will load a set of users from a database using Entity Framework, and display them to
the user. It will also allow adding a new user to the database.
To create a new ASP .NET MVC Application, you will need to create a new project, and go to the Web tab. If you are using Visual
Studio Express for Web, you will immediately see this project option when creating a new project.
In this case, choose the MVC option, then click the Change Authentication button and choose No Authentication. In earlier
editions of Visual Studio, this screen may look a bit different. Be sure to uncheck any additional options if they exist in your
edition. We will not be exploring other templates in this tutorial, but you may try them out if you want they include pre
created demo apps that can be useful for learning.
Visual Studio will create a default application with precreated Models, View and Controllers.
Creating a Model
The Model is the backbone of our application, and therefore we will create it first. In this case, were only have one Model
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
4/22
1443031751619.25
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
publicclassPerson
{
publicstringFirstName{get;set;}
publicstringLastName{get;set;}
publicstringAddress{get;set;}
publicstringEmail{get;set;}
publiclongPhoneNumber{get;set;}
}
As promised, this is a very simple class that has nothing special to it, only plain properties.
Creating a Controller
For now, leave the existing Controllers and Views created by Visual Studio intact. Create a new Controller by right clicking the
Controllers folder and then Add > Controller. In the scaffolding dialog which shows, choose MVC 5 Controller.
Again, if you have an older version of Visual Studio MVC 5 is supported from Visual Studio 2013 and upwards, you may see a
different dialog. Be sure to create an empty MVC controller either way.
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
5/22
1443031751809.951
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
publicActionResultIndex()
{
ViewBag.MyHeader="HelloWorld!";
returnView();
}
Creating a View
Each Action can be associated with a View, without having to explicitly name the View as you could see, the Index method calls
the View method without any parameters. This association is created by another instance of convention over configuration. If
your Action is called Index, ASP .NET MVC will automatically look for a View called Index you can name it differently, and use an
overload of the View method which accepts a View name. Go ahead and create a new View by rightclicking within the Index
Action, then clicking Add View.
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
6/22
1443031752020.924
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
As you can see, Visual Studio already knows how to name this Controller, because youve clicked inside the Index action. Now
go ahead and create the View.
Lets take a look at the result.
Hide Copy Code
@{
ViewBag.Title="Index";
}
<h2>Index</h2>
<ul>
@for(inti=0;i<10;i++)
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
7/22
1443031752241.018
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
{
<li>@i</li>
}
</ul>
As you could intuitively tell, the result of this simple markup block will be a list containing the numbers 0 to 9.
Razor knows that a C# for statement is beginning thanks to the @ character. It then searches for brackets that indicate a block
of code is ahead. Had we not included this character, Razor would treat this as regular text.
Also note how Razor knows to interpret a block of code in the middle of HTML syntax we use the @i statement to indicate
that we want to place the current value of i inside the list item, and we dont need to make a line break or close the tag in either
way. This is only valid if were just printing a member. You cant place a for statement in the same manner, for example.
Code in markup sequences is your familiar C# and .NET, and you may use whatever namespaces you like by adding a @using
statement at the top of the page again, just like a regular class. You may also place breakpoints on Razor markup segments,
which will be triggered at runtime.
If you find yourself writing a lot of code in the View, double check yourself. The View should only contain code that renders the
data from the Controller for textual representation. Code that interacts with the data, performs calls to external resources or can
be even hypothetically reused outside the View, should always go in the Controller.
ViewBag
ViewBag is simply an object thats shared between the Controller and View. Its a useful way of transforming blocks of data
between the two. Note that ViewBag is a dynamic type and not strongly typed determined at runtime, so youll not have
IntelliSense helping you find whats available in the ViewBag object.
There are two more shared objects used for data transfer between Controllers and Views:
ViewData essentially a dictionary where the key is a string and the value is an Object. More efficient with larger sets of
data.
TempData temporary data that is only persistent within the same session, and is mostly useful for preserving data only
for a specific user for a specific session.
Lets try printing out a header in our fresh HTML page from a property on the ViewBag object which we will set from the
Controller.
Switch back to the Controller. In our Index method, just before we return the View, add the following line:
Hide Copy Code
ViewBag.MyHeader="HelloWorld!";
Switch back to the View. Replace the h2 tag with the following:
Hide Copy Code
<h2>@ViewBag.MyHeader</h2>
Now go ahead and press F5 to start debugging. This will launch an instance of your default browser, hosted on a local instance
of IIS Express. The base URL of your website would be http://localhost, followed by a random port number by default you
may change this in the Project Properties window. Paste the following URL in the address form:
http://localhost:99999/Person/Index. Replace the 99999 with the random port number you see when the browser is launched.
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
8/22
1443031752450.479
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
Layout Page
Notice how our brand new View looks pretty nice without us doing any work? This is because of the Layout page. Most web
applications have a consistent look throughout the website same header, menu and footer, as well as additional items that we
might want to make available sitewide. To do this in ASP .NET MVC, we use a Layout page.
The Layout page is a regular View, only its not associated with any Action or Controller. When you create a new View, Visual
Studio will ask you if you want to associate it with a Layout page by default this option is enabled.
By default, the Layout page is called _Layout.cshtml, and it found under the Shared folder under the Views folder. You may
change this default by modifying the _ViewStart.cshtml file.
Hide Copy Code
@{
Layout="~/Views/Shared/_Layout.cshtml";
}
Open the Layout page. Youll notice the RenderBody method is called inside an HTML div. This is where each View will be
rendered.
In ASP .NET MVC 5, the default Layout page loads the Bootstrap CSS library, which means you may use it in any page which
uses the Layout page. This is why the header we just added got a style which is different from the vanilla HTML style.
9/22
1443031752679.122
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
This tutorial will assume that you are familiar with how Entity Framework Code First works, so go ahead and create a simple
PersonManagerDbContext which contains a DbSet of Person. We will store an instance of this data context as a private field
inside our PersonController, and initialize it in the constructor.
Hide Copy Code
privatePersonManagerDataContextmDataContext;
publicPersonController()
{
mDataContext=newPersonManagerDataContext();
}
Now go ahead and populate this table with Persons you can easily do this by creating a Console Application project,
referencing the current project, and adding Person objects to an instance of the PersonManagerDbContext, then calling
context.SaveChanges.
@modelIEnumerable<PersonManager.Models.Person>
@model is a keyword reserved by Razor, and states the current Model type associated with this View. You can then access the
instance of this Model type by using the Model keyword. Notice that capitalization, as usual with C#, matters. Model with a
capital M means a call to the instance of the Model, and model represents the declaration similar to using.
Model is strongly typed, and you can now access the properties of your model class by simply stating the property name.
Obviously we want a list of all our members, so weve specified an IEnumerable of Persons.
Now we need to inject the Person class instance to the View. Go back to your Controller class, and modify the return statement
like this:
Hide Copy Code
returnView(mDataContext.Persons);
Note that this overload of the View method accepts an Object, so if you inject the wrong type of Model class, it will only be
determined at runtime.
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
10/22
1443031752900.79
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
Heres what happens if instead of passing an IEnumerable of Persons, well pass only the first item in the collection, and then run
the application and navigate to the Index Action on the Person Controller:
Copy Code
@usingPersonManager.Models
@modelIEnumerable<PersonManager.Models.Person>
@{
ViewBag.Title="Persons";
}
<h2>Persons</h2>
<tableclass="table">
<thead>
<tr>
<th>#</th>
<th>FirstName</th>
<th>LastName</th>
<th>Address</th>
<th>Phone</th>
<th>Email</th>
</tr>
</thead>
<tbody>
@foreach(PersonpersoninModel)
{
<tr>
<td>@person.PersonId</td>
<td>@person.FirstName</td>
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
11/22
1443031753068.777
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
<td>@person.LastName</td>
<td>@person.Address</td>
<td>@person.PhoneNumber</td>
<td>@person.Email</td>
</tr>
}
</tbody>
</table>
The code is pretty straightforward: were statically declaring an HTML table, creating its head section, and by using a foreach
statement we are dynamically creating table rows, each of which represents a Person retrieved from the database.
Note the using statement for the Person class; this is different from the model statement, and is identical to a using statement
we would use in a traditional class.
[HttpGet]
publicActionResultAddPerson()
{
returnView();
}
[HttpPost]
publicActionResultAddPerson(Personperson)
{
mDataContext.Persons.Add(person);
mDataContext.SaveChanges();
returnRedirectToAction("Index");
}
Notice how we named both Actions the same, for consistency and clearness since one doesnt really exist without the other.
But how would ASP .NET know which Action to access in every use case? Thanks to the [HttpGet] and [HttpPost] attributes.
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
12/22
1443031753285.284
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
When an HTTP GET request hits the /AddPerson route, it will be routed to the first Action, returning a View our friendly form.
An HTTP POST request will be routed directly to the second Action, which naturally accepts a Person object to add to the
database.
Copy Code
publicclassPerson
{
[Key]
[Required]
publicintPersonId{get;set;}
[Required]
[Display(Name="FirstName")]
publicstringFirstName{get;set;}
[Required]
[Display(Name="LastName")]
publicstringLastName{get;set;}
[Required]
publicstringAddress{get;set;}
[Required]
[EmailAddress]
publicstringEmail{get;set;}
[Required]
[Display(Name="PhoneNumber")]
publiclongPhoneNumber{get;set;}
}
There are many more useful attributes with common rules, as well as the RegularExpression attribute, allowing you to customize
the validation pattern using RegEx.
Now go back to the controller, and modify the AddPerson POST Action:
Hide Copy Code
[HttpPost]
publicActionResultAddPerson(Personperson)
{
if(ModelState.IsValid)
{
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
13/22
1443031753492.934
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
mDataContext.Persons.Add(person);
mDataContext.SaveChanges();
RedirectToAction("Index");
}
returnView();
}
ModelState.IsValid will return true if the model weve bound to the View validates correctly against all the attributes weve
placed. In case it doesnt, we wont submit the changes to the database. If the user attempts to submit this form, it will be
validated first, and ASP .NET MVC will automatically display the validation errors once the View is returned we will see how in a
minute.
Finally, as you can probably understand yourself, RedirectToAction will redirect the user to the requested Action when called.
Copy Code
@modelPersonManager.Models.Person
<h2>Addanewpersontothedatabase</h2>
@using(Html.BeginForm())
{
<divclass="formgroup">
@Html.LabelFor(model=>model.FirstName)
@Html.TextBoxFor(model=>model.FirstName,new{Class="formcontrol"})
@Html.ValidationMessageFor(model=>model.FirstName)
</div>
<divclass="formgroup">
@Html.LabelFor(model=>model.LastName)
@Html.TextBoxFor(model=>model.LastName,new{Class="formcontrol"})
@Html.ValidationMessageFor(model=>model.LastName)
</div>
<divclass="formgroup">
@Html.LabelFor(model=>model.Address)
@Html.TextBoxFor(model=>model.Address,new{Class="formcontrol"})
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
14/22
1443031753656.799
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
@Html.ValidationMessageFor(model=>model.Address)
</div>
<divclass="formgroup">
@Html.LabelFor(model=>model.Email)
@Html.TextBoxFor(model=>model.Email,new{Class="formcontrol"})
@Html.ValidationMessageFor(model=>model.Email)
</div>
<divclass="formgroup">
@Html.LabelFor(model=>model.PhoneNumber)
@Html.TextBoxFor(model=>model.PhoneNumber,new{Class="formcontrol"})
@Html.ValidationMessageFor(model=>model.Email)
</div>
<inputtype="submit"class="btnbtndefault"/>
}
Go ahead and run the application, then navigate to the Person/AddPerson route in your browser.
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
15/22
1443031753880.622
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
Place a breakpoint in the beginning of the POST AddPerson method in the Person Controller, add some data to the form and
submit it.
If you add the person variable to the Watch window, youll be able to see the same values youve just entered into the form.
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
16/22
1443031754072.396
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
Lets take a closer look at how this magic just happened. As you can see, weve bound this View to the Person type not a
collection of them this time, because we only want to submit a single Person. Thanks to this, we can use ASP .NET MVCs Form
helpers.
Html.BeginForm() will render the form itself for us, and inject the appropriate URL for submission as the action attribute
of the form tag so that the form will know where to submit itself. By default it will assume we named the GET and POST
Actions the same again, convention over configuration, but there are overloads that allow you to name a different
Action or Controller for submitting the form.
Html.TextBoxFor will create an input of the type text box, but the important part is that it is bound to a specified property
of the Model class! When we submit the form to the server, ASP .NET MVC will inject the value of this textbox as the
matching property of the Model were sending, so in the POST AddPerson method, we can just call person.FirstName or
person.LastName and get the value the user submitted. This is done using a simple Expression accepting the type of the
Model class, as you can see in the code sample.
Html.LabelFor will create a label HTML tag for the input tag of the same property. The default label will simply the name
of the Models property, but you can change that by using the Display attribute over the property in the Model class
take a look at the Person class code sample before.
Html.ValidationMessageFor will display a validation message, according to the validation rules weve defined using
DataAnnotations in the Person Model class.
If you dont use Model Binding, implementing the same logic will be more cumbersome. You would need to write the html tags
yourself, where the value attribute would be something like @ViewBag.MyValue. This is not a recommended approach.
17/22
1443031754253.495
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
bundles.Add(newScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
Bundles are another unique ASP .NET MVC concepts, and are essentially groups of scripts or other types of files as some
JavaScript libraries and frameworks come in several different files. In this case weve created a package which collects all files in
the Scripts folder that contain jquery.validate note the asterisk.
Now go to the Layout page and at the bottom of the page add this line:
Hide Copy Code
@Scripts.Render("~/bundles/jqueryval")
This will render the HTML with the <script> tag linking to all scripts in the Bundle.
And thats all you need to do. If you reload and view the source of the HTML page, youll see something like this:
The data* attributes are special attributes added by ASP .NET MVC, and are parsed by jQuery in order to perform validation.
You can customize the error message displayed by providing an argument to the DataAnnotation attribute on your model class
see the example. This will, again, affect both client and server validation.
What's next?
This is the end of this basic ASP .NET MVC tutorial, but theres much more to learn about this framework. I havent included
these subjects in the tutorial so the examples dont get overwhelming and hard to understand, but I encourage you to read
more about these topics:
Partial Views
Different types of ActionResults what you return from your Action especially JsonResult
Authorization & Authentication Windows & Individual User Accounts
Web API technically, not exactly a part of ASP .NET MVC, but closely related
License
This article, along with any associated source code and files, is licensed under The Code Project Open License CPOL
Share
EMAIL
18/22
1443031754545.981
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
Tal Bronfer
Software Developer
Israel
Software Developer specializing in .NET, Web Development and Software Test Automation.
Go
First Prev Next
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
19/22
1443031754802.662
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
Good Article
Dharmesh .S. Patil 24Jun15 20:28
I give my 5
Sign In ViewThread Permalink
HTTP 404
john_1726 24Apr15 5:46
When I attempt to press F5 under your section "ViewBag" this is what I get:
Hide Copy Code
ServerErrorin'/'Application.
Theresourcecannotbefound.
Description:HTTP404.Theresourceyouarelookingfor(oroneofitsdependencies)could
havebeenremoved,haditsnamechanged,oristemporarilyunavailable.Pleasereviewthe
followingURLandmakesurethatitisspelledcorrectly.
RequestedURL:/Views/Index.cshtml
VersionInformation:Microsoft.NETFrameworkVersion:4.0.30319;ASP.NET
Version:4.0.30319.34248
20/22
1443031755008.048
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
1.00/5 1 vote
Correction
Arjunwalmiki 6Jun14 1:43
pls correct the line of code
Hide Copy Code
<divclass="formgroup">
@Html.LabelFor(model=>model.PhoneNumber)
@Html.TextBoxFor(model=>model.PhoneNumber,new{Class="formcontrol"})
@Html.ValidationMessageFor(model=>model.Email)
</div>
from to
Hide Copy Code
<divclass="formgroup">
@Html.LabelFor(model=>model.PhoneNumber)
@Html.TextBoxFor(model=>model.PhoneNumber,new{Class="formcontrol"})
@Html.ValidationMessageFor(model=>model.PhoneNumber)
</div>
My vote of 5
Renju Vinod 14May14 21:27
Nice
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
21/22
1443031755212.68
ASP.NETMVCforBeginnersinWebDevelopmentCodeProject
5.00/5 1 vote
Move Images
thatraja 5May14 0:21
Host the images on Codeproject which is best option. I can't see the images now. The reason is simple .... Image
hosting websites blocked by most of the workplaces. So better move images.
thatraja
Code converters | Education Needed | Improve EverythingNew
Illustrative!
RahulMGunjal 29Apr14 21:55
Nice article with good details
Sign In ViewThread Permalink
Nice Article!
Ravimal Bandara 29Apr14 2:46
Nice article. Keep writing!
Sign In ViewThread Permalink
Good article...
Dnyaneshwar@Pune 28Apr14 3:30
Good article...
Sign In ViewThread Permalink
Refresh
General
News
1
Suggestion
Question
Bug
Answer
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment
Joke
Rant
Admin
22/22