Click here to Skip to main content
15,868,340 members
Articles / Web Development / ASP.NET

Creating a simple application using MVC 4.0

Rate me:
Please Sign up or sign in to vote.
4.79/5 (131 votes)
21 Feb 2013CPOL6 min read 1M   40.5K   178   231
Creating simple application using MVC4.0.

Introduction 

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.

Image 1

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

Image 2

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”

Image 3

A solution with following structure is added.

Image 4

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

Image 5

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: 

Image 6

Now let’s apply validations on the fields:

Image 7

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

Image 8

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

Image 9

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. 

Image 10

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

Image 11

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.

Image 12

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. 

Image 13

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.

C#
public ContentResult Test() 
{
    return Content("This is my test data");
}

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

C#
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. 

C#
public PartialViewResult Test() 
{ 
    return PartialView("Result");
}

ViewResult: It renders a specified view. 

C#
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. 

Image 14

MVC routing pattern include {controller} and {action} placeholder. For more details on routing please refer this link http://msdn.microsoft.com/en-us/library/cc668201.aspx 

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

Image 15

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

Image 16

ViewBag, ViewData and TempData:

ViewData:
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.
ViewBag:
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.
TempData:
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.

License

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


Written By
Program Manager Infobeans
India India
I have keen interest in learning new things, exploring more on a topic and being more versatile

Comments and Discussions

 
AnswerRe: with database Pin
Anuja Pawar Indore15-Mar-15 19:51
Anuja Pawar Indore15-Mar-15 19:51 
GeneralReally helpful MAM :-) Pin
parulrai38623-Feb-15 21:19
parulrai38623-Feb-15 21:19 
GeneralRe: Really helpful MAM :-) Pin
Anuja Pawar Indore11-Mar-15 19:47
Anuja Pawar Indore11-Mar-15 19:47 
Questionmvc4 Pin
Member 114232643-Feb-15 19:45
Member 114232643-Feb-15 19:45 
AnswerRe: mvc4 Pin
Anuja Pawar Indore3-Feb-15 19:52
Anuja Pawar Indore3-Feb-15 19:52 
QuestionProblem while creating view Pin
R H Patel21-Dec-14 20:19
professionalR H Patel21-Dec-14 20:19 
AnswerRe: Problem while creating view Pin
Anuja Pawar Indore11-Mar-15 19:50
Anuja Pawar Indore11-Mar-15 19:50 
QuestionThe view is not created as displayed here Pin
Member 1111011130-Oct-14 9:10
Member 1111011130-Oct-14 9:10 
HI Anuja,
I am totally new to MVC. I followed the steps you have provided and trying to create my own project. I have all the fields and methods defined but unfortunately my view is not generated as shown here Can you Help me.
AnswerRe: The view is not created as displayed here Pin
Anuja Pawar Indore30-Oct-14 19:42
Anuja Pawar Indore30-Oct-14 19:42 
GeneralRe: The view is not created as displayed here Pin
Member 1111011131-Oct-14 2:44
Member 1111011131-Oct-14 2:44 
QuestionWhere to declare the validations on fields Pin
Member 1116690720-Oct-14 3:49
Member 1116690720-Oct-14 3:49 
QuestionProblem Pin
Member 1107817717-Oct-14 23:32
Member 1107817717-Oct-14 23:32 
AnswerRe: Problem Pin
Anuja Pawar Indore19-Oct-14 20:53
Anuja Pawar Indore19-Oct-14 20:53 
QuestionNice one......... Pin
Raghvendra Singh Verma9-Oct-14 18:21
Raghvendra Singh Verma9-Oct-14 18:21 
AnswerRe: Nice one......... Pin
Anuja Pawar Indore11-Mar-15 19:49
Anuja Pawar Indore11-Mar-15 19:49 
GeneralMy vote of 1 Pin
raoraorao2-Aug-14 7:15
raoraorao2-Aug-14 7:15 
GeneralRe: My vote of 1 Pin
Anuja Pawar Indore3-Aug-14 21:03
Anuja Pawar Indore3-Aug-14 21:03 
QuestionThank u.. Pin
Anusha Rose24-Jul-14 22:38
Anusha Rose24-Jul-14 22:38 
AnswerRe: Thank u.. Pin
Anuja Pawar Indore24-Jul-14 23:17
Anuja Pawar Indore24-Jul-14 23:17 
GeneralThank You.... Pin
champike de seram30-Jun-14 2:12
champike de seram30-Jun-14 2:12 
GeneralRe: Thank You.... Pin
Anuja Pawar Indore30-Jun-14 20:59
Anuja Pawar Indore30-Jun-14 20:59 
QuestionGood Example Pin
Member 898643324-Jun-14 5:02
Member 898643324-Jun-14 5:02 
AnswerRe: Good Example Pin
Anuja Pawar Indore24-Jun-14 19:51
Anuja Pawar Indore24-Jun-14 19:51 
QuestionNice Article Pin
Manohar_manu3-Jun-14 0:38
Manohar_manu3-Jun-14 0:38 
AnswerRe: Nice Article Pin
Anuja Pawar Indore3-Jun-14 2:26
Anuja Pawar Indore3-Jun-14 2:26 

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.