You are on page 1of 22

1443031750582.

265

ASP.NETMVCforBeginnersinWebDevelopmentCodeProject

11,765,758 members 56,044 online

articles

Q&A

Sign in

forums

lounge

Searchforarticles,questions,tips

ASP .NET MVC for Beginners in Web Development


Tal Bronfer, 29 Apr 2014

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 are Web Application Frameworks?


Put simply, Web Application Frameworks allow you to create applications which generate HTML pages typically, though there
are other types of responses which we will brush on later dynamically, rather than storing precreated HTML pages on your
web server.
This allows the creation of powerful, smart websites that do way beyond displaying static data. Most dynamic websites
meaning websites that do not only display static HTML pages in the world today are created using some sort of a Web
Application Framework.

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.

What is Microsoft ASP .NET MVC?


Simply put, ASP .NET today can be referred to as the set of technologies and libraries that underlies the ASP .NET MVC
Framework.

ASP .NET Web Forms


ASP .NET Web Forms is what .NET developers used to call ASP .NET, prior to the introduction of ASP .NET MVC hence the
confusion. It introduced concepts that are similar to developing Windows Forms applications including draggable controls,
page state and codebehind files.
The main advantage of ASP .NET Web Forms is the ease of creating a Web Application, which can initially be created with little
to no code at all, using controls from the Toolkit. However, Web Forms doesnt enforce modern design patterns, may
sometimes create cluttered and nonstandard HTML pages and couples the user to Microsoft controls & JavaScript libraries.
ASP .NET Web Forms still lives and is used by many .NET developers.

ASP .NET MVC


ASP .NET MVC was introduced in 2008 and is based on the ASP .NET stack, as a competitor to existing, prominent open source
MVC Web Application Frameworks such as Ruby on Rails and Django. Like them, ASP .NET MVC is open sourced.
The main advantage of ASP .NET MVC is that it is more flexible, and allows you to use external libraries, implement your own
logic, and creates clean, compatible HTML pages and application logic that is easily testable. It does, however, require a steeper
learning curve and generally speaking, more code.

Your First ASP .NET Application - PersonManager


Creating a new ASP .NET MVC application
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment

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.

Convention over Configuration


ASP .NET MVC follows the popular Convention over Configuration principle, which favors naming conventions over complex
configuration files that define whats what.
To get started with ASP .NET MVC, familiarize yourself with the following conventions:
Controllers must be named in the syntax NameController and are placed in the Controllers folder.
Views dont have a specific naming convention, but must be placed in the Views folder.
Application Data, such as additional configuration files, binary files or local database files, should be placed in the
App_Data folder.

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

person. Lets create that class in the Models folder.


Hide Copy Code

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

Name your controller PersonController. Remember the controller naming convention!


As you can see, this brand new controller is a simple class which inherits from Controller, and contains only one method
Index, which returns the View associated with this Action.
Hide Copy Code

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>

ASP .NET MVC Razor Markup Syntax


As you can see, this page has HTML tags, but it also has a special syntax, the @ character, which indicates a block of C# code,
and not HTML, is ahead. This is called markup syntax the core of the magic of ASP .NET or any Web Application Framework,
for that matter. This is what allows you to create dynamic content and not just write static HTML pages.
ASP .NET MVC supports different view engines, which are responsible for rendering the Views HTML. The default view engine
is called Razor and was designed for ASP .NET MVC, and for our purposes, there are no reasons for using a different one.
Different view engines may have different markup syntaxes for example, the classic ASP .NET engine uses <% tags.
Razor has a pretty smart markup syntax, that doesnt need terminating tags like some other engines do. For example, you may
do the following:
Hide Copy Code

<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

ASP .NET MVC Routing


It worked! You can see that the routing is pretty intuitive we went to the Person controller and then to the Index Action.
Notice how we didnt use PersonController as the Controller name this is part of the ASP .NET MVC Controller naming
convention. Now go back to the browser and remove the Index segment from the URL you can see that the page still loads
correctly; again, more convention over configuration when no Action name is provided, ASP MVCs default routing system will
search for an Action called Index. This helps create cleaner, search engine friendly URLs.
You can create custom and more sophisticated routing rules by modifying the RouteConfig class under the App_Start folder.

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.

Creating a repository for your Model


Now lets get back to planning our application. We need to create a repository that will store the Persons in our application.
Well do this using Entity Framework.
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment

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.

Binding View to the Model


So now we can easily access the Persons in our database by calling mDataContext.Persons. But how do we make this available
to the View?
One way would be using one of the shared objects ViewBag or ViewData. We could add a Person property on the ViewBag
and access it from the View. This approach has several problems associated with it:
Necessary casting you will need to cast the properties back to string or whatever type they are. This causes another
instance of boxing and unboxing by the CLR, and is less efficient. But more importantly, it may lead to unnecessary
runtime cast errors.
Dynamic typing no IntelliSense is available as types are resolved at runtime. Even when using the ViewData dictionary,
you cannot know at compile time if you havent made a typo in the key value.
Performance implications In addition to the performance impact caused by the casting required, dynamic types and
Dictionaries are less efficient than strong types and Collections. On smaller scales this wouldnt be noticeable, of course.
To avoid this, we can make the model instance available to the View. To do this, open the Index view we worked on earlier, and
add the following line in the top of the page:
Hide Copy Code

@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:

Displaying the Model


Now that we have our Model available, we can build our page using Razor markup. This is what the markup looks like:
Hide Shrink

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.

Implementing Actions for adding a person


Now well implement the addition of a new Person to the repository. For this we will need to create two Actions:
GET Action this Action will be called by the browser initially to display the submission form to the user.
POST Action this Action will be called by the form when we submit it.
But should we create two Views? Not necessarily! Only the GET Action needs to actually return a View. After submitting the
form, we may just want to redirect the user back to the homepage.
Lets implement these two Actions:
Hide Copy Code

[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.

Adding serverside validation


One of the basic rules of designing any useroriented application is to never trust your user. We want to make sure all fields are
populated with data and perform other basic tests before adding the data to our database.
We could do this by adding a series of clumsy if statements over the Person parameter, but this would be a bit tough to read.
And what if we want to apply these rules again somewhere else? Well just repeat the code.
ASP .NET helps us with validation using the Data Validation attributes System.ComponentModel.DataAnnotations directly over
our Model class. Feel free to explore this namespace on MSDN on your own. For now, lets add a few of these attributes.
Hide Shrink

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.

Creating a form and submitting data


Lets go back to the AddPerson GET Action, and add a new View. Paste the following code:
Hide Shrink

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.

Adding HTML attributes in ASP .NET MVC HTML helpers


Many of ASP .NET MVCs HTML helpers generate handy HTML for us, but what if we want to customize the HTML? for example,
add a class attribute to style a Text Box created by the TextBoxFor helper
We can do this quite simply, by using an overload of the helper which accepts an Object containing the HTML attributes we
want to add. Take a look at the example above. Ive created an object which only contains a string property named Class which
ASP .NET MVC will add as a Class attribute. You can add any type and combination of HTML attributes, even nonstandard ones
such as ones used for jQuery data manipulations and such.

Adding clientside validation


Remember us saying never trust the user? While this is true, we also dont want to make the user send the form to the server
and wait for a response only to realize he had forgotten one field. We also want to avoid this unnecessary traffic to the server.
This is where clientside validation comes to play. There are various ways of implementing this, either via HTML 5 which is only
supported in modern browsers or via libraries such as jQuery which has wider support.
ASP .NET MVC has a cool feature which automatically implements jQuery clientside validation using the rules that we have set
up using the DataAnnotations attributes. This allows us, again, to define the validation rules in only one place.
Note that clientside validation should never be trusted on its own, because if JavaScript is disabled in the users browser, it
wont trigger. You should always have serverside validation.
To do this, you need to install the NuGeT package called Microsoft jQuery Unobtrusive Validation. After the installation has
finished, add it as a Bundle to the BundleConfig.cs file, like this:
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment

17/22

1443031754253.495

ASP.NETMVCforBeginnersinWebDevelopmentCodeProject

Hide Copy Code

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

TWITTER

About the Author


http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment

18/22

1443031754545.981

ASP.NETMVCforBeginnersinWebDevelopmentCodeProject

Tal Bronfer
Software Developer
Israel
Software Developer specializing in .NET, Web Development and Software Test Automation.

You may also be interested in...


Classic ASP and MVC

Developer Tips for Scanning on


the Web

MVC on Azure for Beginners

Scan Anything, Anywhere, Any


Time

First MVC Application for


Beginners

Getting Started with the Intel


Edison Board on Windows

Comments and Discussions

You must Sign In to use this message board.


Search Comments

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

Do you have any suggestions? What am I missing? TIA.


Sign In ViewThread Permalink

Re: HTTP 404


john_1726 24Apr15 9:53
OK, got it, this is the URL I need to access, say:
http://localhost:52101/Person/Index[^]
Sign In ViewThread Permalink

Nice Article Keep Going


chandruvelan 15Apr15 19:02
Nice Artical Keep going

Sign In ViewThread Permalink

Beginner ASP.NET MVC Tutorials


Member 8026617 11Oct14 21:37
http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment

20/22

1443031755008.048

ASP.NETMVCforBeginnersinWebDevelopmentCodeProject

Beginner ASP.NET MVC Tutorials...


Beginner ASP.NET MVC Tutorials
http://studyoverflow.com/aspmvc
Sign In ViewThread Permalink

1.00/5 1 vote

ASP.NET MVC Development Company


Aum InfoTech 27Aug14 2:51
This is the very nice article. MVC gives so much security.
If anyone want to any asp.net mvc development company, i can recommend AUM InfoTech.
Sign In ViewThread Permalink

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>

Sign In ViewThread Permalink

My vote of 5
Renju Vinod 14May14 21:27
Nice

http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment

21/22

1443031755212.68

ASP.NETMVCforBeginnersinWebDevelopmentCodeProject

Sign In ViewThread Permalink

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

Sign In ViewThread Permalink

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

Permalink | Advertise | Privacy | Terms of Use | Mobile


Web02 | 2.8.1509020.2 | Last Updated 29 Apr 2014

Bug

Answer

Layout: fixed | fluid

http://www.codeproject.com/Articles/765519/ASPNETMVCforBeginnersinWebDevelopment

Joke

Rant

Admin

Article Copyright 2014 by Tal Bronfer


Everything else Copyright CodeProject, 19992015

22/22

You might also like