Click here to Skip to main content
Click here to Skip to main content

First MVC Application for Beginner's

, 18 Aug 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
This article will step by step guide you through the Flow of MVC application clearing your basic concepts of MVC

Introduction

Hello guys, In this article i am going to create a sample project to explain how the control flow between model-controller-view. This article is for absolute beginner's and can be considered as First step in learning MVC. I decided to post this article because when i started learning MVC without any guidance i found it bit confusing. So i assume that there might be so many like me who are learning MVC on their own. Thus, this article is just to guide an absolute beginner to MVC.

Here, We will make an application where on home page we will have a hyperlink named click. on clicking that link user will be navigated to the view which displays list of person.

Using the code

 

I have used Visual Studio 2013 but you can also work with Visual Studio 2012. In Visual Studio create a new project named UrlMapping.

Go to: File-->New-->Project.

 

In the Web section, select  MVC 4 Web Application under .NET Framework 4.5 and name it UrlMapping. Click OK.  You will be directed to the templates window. There select the Empty Application template. Here you can also work with Internet Application. But to make things simple and less confusing, i have chosen Empty Application. In the later articles i will make use of Internet Application.

 

Select the Razor engine as your View Engine.

.NET Framework provides you two View Engines: Razor and ASPX. We will discuss about view Engines in the later articles. As of now we will work with Razor view Engines.

 

Once you click OK, your appliction will be created which will contain some folders like Model, View, Controllers, App_Start, App_Data.

Understanding the Folders:

Model:  This folder contains classes that is used to provide data. These classes can contain data that is retrived from the database or data inserted in the form by the user to update the database.

Controllers: These are the classes which will perform the action invoked by the user. These classes contains methods known as "Actions" which responds to the user action accordingly.

Views: These are simple pages which uses the model class data to populate the HTML controls and renders it to the clent browser.

App_Start: Contains Classes such as FilterConfig, RoutesConfig, WebApiConfig. As of now we need to understand the RouteConfig class. This class contains the default format of the url that should be supplied in the browser to navigate to a specified page.

Such As:

 public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Person", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

 

Here, MapRoute is an extension method and its property "url" is used to set the format of url, by default the format specified is that url should be as {controller's name}/{action's name}/{parameter(optional)}

You can change this format as you need. But this is the standarised format. the third section of the url that is {id} is optional.

Creating Model Class:

First of all, let's create a model class to work with.  Add a class to the model folder. Right click model folder--> Add--> class. Name it Person.cs and click Add button.

A Person class will be added to your model folder. Now create two automated properties like :

public class Person

{

	public string FirstName { get; set; }

	public string LastName { get; set; }

}

We will be using this class to provide data to the view.

Creating a Controller:

To use the Person class we will need a controller. As controller handles the user request and the logic of your application is contained in the controller.

So let's add a controller. Right click the controller folder--> Add--> Controller. Name it PersonController and click Add button.

A controller will be added to the controller folder containing Index action method by default. Remember methods of controller class are referred to as actions.

Creating View of a particular action:

Now to interact with the user we need a User Interface. For that we need a view. It acts as a presentation layer of our application.

So add a view named Index. Right click index action method-->Add View-->Click Add button.  A view will be added to the Person Folder in View folder. Notice that the person folder is created automatically and usually the name of the folder corressponds to the name of the controller. By default there will be some code in the Index view page.

Add the following code to your Index view:

'@' is called code delimiter similiar to <%%> used in ASPX pages.

'@' is used to write code when using Razor view engine. 'Html' is a helper class used to create Html controls such as text boxes, dropdownlist, label, link ,etc. In order to create a hyperlink we used ActionLink method. There are 10 overloads of ActionLink method.

We have used an overloaded version of ActionLink method. that is ActionLink(string linkText, string actionName, string controllerName).

@Html.ActionLInk("Click","Click","Person") : This line of code creates a hyperlink with text "Click", which when clicked responds to a Click action in the Person Controller.

Now run your application by pressing Ctrl+F5. You will get a "resourse not found" error such as:

The reson you see this page as soon as you run your application is that in your RouteConfig class the default values of the controller and action provided are: Home as controller and Index as Action. So when you run your application the .NET Framework searches your application for a controller named "Home" but it cannot find it as our application doesn't contain any controller named "Home". So to resolve this error. Set the value of controller to "Person". Such as:

 

defaults: new { controller = "Person", action = "Index", id = UrlParameter.Optional }

Now run you application. It displays the page saying "Index" containing a link called Click. What is hapening here is when you run your application the .NET Framework searches the entire application for controller named Person. Once found it then searches for the action method named Index() in the PersonController as we have provided action name as Index in our RouteConfig class. Once Index action is found then it executes the code contained in Index action. That is

public ActionResult Index()

{

	return View();

}

Since our Index action returns a view(). Now notice that here the name of View is not specified then how will .NET Framework know which View to call. What .NET Framework does is that it searches for the view named as the name of action.That is it searches for the Index view and executes the code of Index view which is rendered to the client browser. And thus we see a "Click" hyperlink

This concludes that to set your default home page of your application do the required changed in the RouteConfig class.

Now, Click the link "Click". As soon as you click the link you will get another error. Such As

You see this page because when you click the link it navigates you to the click action in person controller. But our application doesn't contain any action named click. Thus to resolve this error add an action method named Click in the person controller as

public ActionResult Click()

{

	Person person = new Person();

	List<person> persons = new List<person>() 

	{ 

		new Person { FirstName = "Sherlock", LastName = "Holmes" }, 

		new Person { FirstName = "James", LastName = "Watson" } 

	};

	return View(persons);

}
</person></person>

In this action we are creating an instance to our Person model class. As our motive is to populate the view with the list of Person. So i have created a list<> of Person and hardcoded some values to the Person object and added it to the list. And further i have supplied this List to the View.

Now notice that, Here view named click will be returned. Since our application doesn't contain a view named click. Lets add one to our application.

Right click on Click action method-->

Add view-->check the checkbox for create a strongly typed view-->

From Model class drop down select Person(UrlMapping.Model)-->

From Scaffold template drop down select 'List'--> click add button. Now a view will be added to the Person folder in the View folder.

Now modify the click view as

 Now run your application. And it work as expected

Flow of control between Controller-Model-View

The control flow in this manner: 1-->2-->3-->4

 It first goes from controller to model if used then from model back to the controller and then to the view.

From PersonController--> Person Model

Then Person Model-->PersonController -->ClickView. (as we clicked the link which takes us to the Click action method which in turn returns Click view

Points of Interest

I have skipped explanation of some codes. As this was the First step to MVC. You will learn everything you need as you proceed. I will be posting article of the the next step to learn MVC. Till then best of luck.

License

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

Share

About the Author

Singh Deepika
Software Developer (Junior)
India India
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun25-Nov-14 16:01 
GeneralThanks PinmemberMember 1040652324-Aug-14 3:35 
GeneralMy vote of 4 PinmemberDMB3335121-Aug-14 5:37 
GeneralMy vote of 2 PinprofessionalMember 10284041 VJ20-Aug-14 21:56 
GeneralRe: My vote of 2 PinmemberSingh Deepika20-Aug-14 23:08 
GeneralRe: My vote of 2 PinmemberDarshil H Pandya2-Sep-14 0:03 
GeneralRe: My vote of 2 PinmemberSingh Deepika2-Sep-14 1:25 
GeneralMy vote of 3 PinprofessionalJim Adamski20-Aug-14 14:23 
QuestionThanks PinmemberMohammad Rahil20-Aug-14 10:07 
QuestionMy Vote of 4 Pinmembernewton.saber20-Aug-14 3:25 
QuestionIs it right Flow of control between Controller-Model-View which u give here PinmemberTridip Bhattacharjee19-Aug-14 22:33 
GeneralMy vote of 2 Pinmvp Akhil Mittal 19-Aug-14 20:29 
General[My vote of 2] My vote of 2 Pinmvp Akhil Mittal 19-Aug-14 20:28 
SuggestionNice as the first post... PinprofessionalAfzaal Ahmad Zeeshan19-Aug-14 10:15 
GeneralMy vote of 1 PinmemberSidd-B19-Aug-14 8:53 
QuestionSimple and Good PinprofessionalGihan Liyanage19-Aug-14 0:26 
QuestionExcellent Article.. PinmemberKapil K Jain18-Aug-14 23:53 
QuestionGreat PinmemberNikhil Barapatre18-Aug-14 23:53 
QuestionExcellent PinmemberMember 1032009218-Aug-14 23:48 
GeneralGood Pinmemberady cody18-Aug-14 23:27 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun18-Aug-14 21:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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.1411023.1 | Last Updated 19 Aug 2014
Article Copyright 2014 by Singh Deepika
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid