Click here to Skip to main content
11,927,378 members (47,434 online)
Click here to Skip to main content
Add your own
alternative version


166 bookmarked

Creating a simple application using MVC 4.0

, 21 Feb 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Creating simple application using MVC4.0.


In this article, we will understand what is MVC and create a simple application using Model, View and Controller.     

Model View Controller: MVC is a software architecture, which separates the logic from the user interface. This is achieved by separating the application into three parts Model, View and Controller. MVC is separation of concern. MVC is also a design pattern.

Model: Represents the logical behavior of data in the application. It represents applications business logic. Model notifies view and controller whenever there is change in state.

View: Provides the user interface of the application. A view is the one which transforms the state of the model into readable HTML. 

Controller: Accepts inputs from the user and instructs the view and model to perform the action accordingly.

Advantages of MVC:

  1. Full control over HTML rendered. No renaming of HTML IDs
  2. Provides clean separation of concerns (SoC).
  3. No ViewState (Stateless). 
  4. Enables Test Driven Development (TDD). 
  5. Easy integration with JavaScript frameworks.
  6. RESTful URLs that enables SEO. Representational state transfer URLs example User/Comment/1, which is user friendly, no URL rewriting required. 
  7. Integration on the client side becomes easy like using JavaScript, JQuery, Ajax, JSON…. 
  8. Supports multiple view engines (aspx, Razor)

Creating a simple application: 

Step-1: From file select project and select MVC 4.0 application

Step-2:Select the template and view engine (Razor, ASPX, NHaml, Spark). If want to include test project check the option “Create unit test project”

A solution with following structure is added.

Build and run the application, you can see the home page of the application. By default we have Home, About and Contact section added. 

Let’s add our own Controller, Model and View for showing User’s details. Right click on Model and add a class with the name UserModels.cs with the following structure: 

Now let’s apply validations on the fields:

  • Required: To make the field value mandatory. 
  • StringLength: To set the maximum length of the field.
  • Range: To set the minimum and maximum value.
  • DataType: To set the type supported by the field. 

Let’s add some default data to our view. For that we will create a class called user and initialize with some default value. 

Now let’s add methods for Adding, Updating and getting list of all users. 

Now let’s add view for our model for that we will select strongly-typed view and select our model class. You can see list of scaffold templates available. Since we are creating this view to add a new user we will select Create option. 

The moment we click on Add, below is the cshtml created for the view

We can see the view is having all the fields set in the model along with the validations applied on it.

Now let’s add a controller for our view. Right click on controller folder name our controller as User, select Empty MVC controller and Add.

By default our controller contains an Index method. Right click on the index method and add view for this. Index method can be used to show the list of user’s available. So we can select scaffold template type as list.

Once the view is added for Index and UserAdd, we have to define its get and post method in the controller. By default its always get, if we want a post method we have to define [httppost] before the method declaration.

HttpGet: will render the form and HttpPost will post the form data. For example we need to add a new user. First we need the form to add a user, that is get and when we will the form with values we need to post those values, so that it can be saved for further access.

Look at our controller structure, it contains two get methods, one to get the list of users (Index) and other to get the UserAdd form and with the same name it contains its post method. 

ActionResult: An action result represents a command that the framework will perform on behalf of the action method. The ActionResult class is the base class for action results. Common return Type:    

ContentResult: Can be used to return plain text or user defined content type.

public ContentResult Test() 
    return Content("This is my test data");

JsonResult: Used to return JSON, mainly used for Ajax request.

public JsonResult Test() 
    return Json ("This is my test json data");

PartialViewResult: The PartialViewResult class is inherited from the abstract "ViewResultBase" class and is used to render a partial view. 

public PartialViewResult Test() 
    return PartialView("Result");

ViewResult: It renders a specified view. 

public ViewResult Test() 
   return View("Result"); 

FileResult: It is used when we want to return the binary content/file as an output.

RedirectToRouteResult:  It is uesd when we want to redirect to another action method.

JavaScriptResult: If we want our action method to return a script that can be executed on the client side we can use this type.

Three new types which are supported from MVC 3

  1. HttpNotFound: This returns 404 error on client side. It can be useful in situations where the resource is not available and we want to display 404. 
  2. RedirectResult It can be a temporary or permanent return code 302 depending upon the boolean flag. Can be used to redirect to the given URL
  3. HttpStatusCodeReturn: It can be used when user want's the choice of error code to be returned from the action method. It can be any code.

Routing with MVC

MVC gives great flexibility for adding user friendly URL’s.  Routings are defined under the class RouteConfig. By default one route is already defined. 

MVC routing pattern include {controller} and {action} placeholder. For more details on routing please refer this link 

This is how our index page will appear with the URL:

And the UserAdd method, here controller is User and Action is UserAdd

ViewBag, ViewData and TempData:

1. ViewData is a dictionary object that is derived from ViewDataDictionary class.
2. ViewData is used to pass data from controller to corresponding view.
3. It’s life lies only during the current request.
4. If redirection occurs then it’s value becomes null.
5. It’s required typecasting for complex data type and check for null values to avoid error.
1. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
2. Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
3. It’s life also lies only during the current request.
4. If redirection occurs then it’s value becomes null.
5. It doesn’t required typecasting for complex data type.
1. TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
2. TempData is used to pass data from current request to subsequent request means incase of redirection.
3. It’s life is very short and lies only till the target view is fully loaded.
4. It’s required typecasting for complex data type and check for null values to avoid error.
5. It is used to store only one time messages like error messages, validation messages.

Points of Interest

More keen in learning MVC 4.0 new features. Lets learn to build a simple application then we can move ahead with advanced features.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Anuja Pawar Indore
Program Manager Diaspark
India India
I have keen interest in learning new things, exploring more on a topic and being more versatile

You may also be interested in...

Comments and Discussions

Questionmvc 4 Pin
Member 105059297-Oct-15 20:27
memberMember 105059297-Oct-15 20:27 
AnswerRe: mvc 4 Pin
Anuja Pawar Indore7-Oct-15 20:55
memberAnuja Pawar Indore7-Oct-15 20:55 
Questionwhere that user class to be added in model or else in the controller Pin
Member 1202176030-Sep-15 3:02
memberMember 1202176030-Sep-15 3:02 
AnswerRe: where that user class to be added in model or else in the controller Pin
Anuja Pawar Indore30-Sep-15 21:09
memberAnuja Pawar Indore30-Sep-15 21:09 
QuestionWith Database Pin
Member 1174040324-Aug-15 1:21
memberMember 1174040324-Aug-15 1:21 
AnswerRe: With Database Pin
Rohan Leuva24-Aug-15 1:22
protectorRohan Leuva24-Aug-15 1:22 
QuestionView 'User' is not found Pin
Member 118214668-Jul-15 1:50
memberMember 118214668-Jul-15 1:50 
AnswerRe: View 'User' is not found Pin
Anuja Pawar Indore8-Jul-15 21:22
memberAnuja Pawar Indore8-Jul-15 21:22 
QuestionError: String was not recognized as a valid DateTime Pin
Member 118126214-Jul-15 2:02
memberMember 118126214-Jul-15 2:02 
GeneralMy vote of 5 Pin
Saravanan21122-Jun-15 21:59
professionalSaravanan21122-Jun-15 21:59 
Questionedit, delete? Pin
Jun Wei Ng21-Jun-15 16:06
memberJun Wei Ng21-Jun-15 16:06 
AnswerRe: edit, delete? Pin
Anuja Pawar Indore22-Jun-15 1:11
memberAnuja Pawar Indore22-Jun-15 1:11 
QuestionError Not able to show the user page Pin
IndrajitDasgupat11-Jun-15 23:39
memberIndrajitDasgupat11-Jun-15 23:39 
AnswerRe: Error Not able to show the user page Pin
Anuja Pawar Indore12-Jun-15 0:00
memberAnuja Pawar Indore12-Jun-15 0:00 
GeneralRe: Error Not able to show the user page Pin
IndrajitDasgupat12-Jun-15 0:14
memberIndrajitDasgupat12-Jun-15 0:14 
QuestionDate Picker Issue Pin
Member 117453045-Jun-15 11:28
memberMember 117453045-Jun-15 11:28 
AnswerRe: Date Picker Issue Pin
Anuja Pawar Indore9-Jun-15 2:39
memberAnuja Pawar Indore9-Jun-15 2:39 
Questionmake me conform Pin
Member 1169297415-May-15 1:54
memberMember 1169297415-May-15 1:54 
AnswerRe: make me conform Pin
Anuja Pawar Indore9-Jun-15 2:43
memberAnuja Pawar Indore9-Jun-15 2:43 
GeneralGood Example Pin
Member 1131980813-Mar-15 20:41
memberMember 1131980813-Mar-15 20:41 
GeneralRe: Good Example Pin
Anuja Pawar Indore15-Mar-15 20:50
memberAnuja Pawar Indore15-Mar-15 20:50 
GeneralMy vote 5 Pin
Nitin Sawant10-Mar-15 3:38
professionalNitin Sawant10-Mar-15 3:38 
GeneralRe: My vote 5 Pin
Anuja Pawar Indore11-Mar-15 20:47
memberAnuja Pawar Indore11-Mar-15 20:47 
Questionwith database Pin
Member 1145833426-Feb-15 3:18
memberMember 1145833426-Feb-15 3:18 
AnswerRe: with database Pin
Anuja Pawar Indore15-Mar-15 20:51
memberAnuja Pawar Indore15-Mar-15 20:51 
GeneralReally helpful MAM :-) Pin
parulrai38623-Feb-15 22:19
memberparulrai38623-Feb-15 22:19 
GeneralRe: Really helpful MAM :-) Pin
Anuja Pawar Indore11-Mar-15 20:47
memberAnuja Pawar Indore11-Mar-15 20:47 
Questionmvc4 Pin
Member 114232643-Feb-15 20:45
memberMember 114232643-Feb-15 20:45 
AnswerRe: mvc4 Pin
Anuja Pawar Indore3-Feb-15 20:52
memberAnuja Pawar Indore3-Feb-15 20:52 
QuestionProblem while creating view Pin
Member 1024007421-Dec-14 21:19
memberMember 1024007421-Dec-14 21:19 
AnswerRe: Problem while creating view Pin
Anuja Pawar Indore11-Mar-15 20:50
memberAnuja Pawar Indore11-Mar-15 20:50 
QuestionThe view is not created as displayed here Pin
Member 1111011130-Oct-14 10:10
memberMember 1111011130-Oct-14 10:10 
AnswerRe: The view is not created as displayed here Pin
Anuja Pawar Indore30-Oct-14 20:42
memberAnuja Pawar Indore30-Oct-14 20:42 
GeneralRe: The view is not created as displayed here Pin
Member 1111011131-Oct-14 3:44
memberMember 1111011131-Oct-14 3:44 
QuestionWhere to declare the validations on fields Pin
Member 1116690720-Oct-14 4:49
memberMember 1116690720-Oct-14 4:49 
QuestionProblem Pin
Member 1107817718-Oct-14 0:32
memberMember 1107817718-Oct-14 0:32 
AnswerRe: Problem Pin
Anuja Pawar Indore19-Oct-14 21:53
memberAnuja Pawar Indore19-Oct-14 21:53 
QuestionNice one......... Pin
Raghvendra Singh Verma9-Oct-14 19:21
memberRaghvendra Singh Verma9-Oct-14 19:21 
AnswerRe: Nice one......... Pin
Anuja Pawar Indore11-Mar-15 20:49
memberAnuja Pawar Indore11-Mar-15 20:49 
GeneralMy vote of 1 Pin
raoraorao2-Aug-14 8:15
memberraoraorao2-Aug-14 8:15 
GeneralRe: My vote of 1 Pin
Anuja Pawar Indore3-Aug-14 22:03
memberAnuja Pawar Indore3-Aug-14 22:03 
QuestionThank u.. Pin
Member 1050816524-Jul-14 23:38
memberMember 1050816524-Jul-14 23:38 
AnswerRe: Thank u.. Pin
Anuja Pawar Indore25-Jul-14 0:17
memberAnuja Pawar Indore25-Jul-14 0:17 
GeneralThank You.... Pin
champike de seram30-Jun-14 3:12
memberchampike de seram30-Jun-14 3:12 
GeneralRe: Thank You.... Pin
Anuja Pawar Indore30-Jun-14 21:59
memberAnuja Pawar Indore30-Jun-14 21:59 
QuestionGood Example Pin
Member 898643324-Jun-14 6:02
memberMember 898643324-Jun-14 6:02 
AnswerRe: Good Example Pin
Anuja Pawar Indore24-Jun-14 20:51
memberAnuja Pawar Indore24-Jun-14 20:51 
QuestionNice Article Pin
Manohar_manu3-Jun-14 1:38
groupManohar_manu3-Jun-14 1:38 
AnswerRe: Nice Article Pin
Anuja Pawar Indore3-Jun-14 3:26
memberAnuja Pawar Indore3-Jun-14 3:26 
Questionerror Pin
Member 1083124620-May-14 1:03
memberMember 1083124620-May-14 1:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.151126.1 | Last Updated 22 Feb 2013
Article Copyright 2012 by Anuja Pawar Indore
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid