Introduction:
This article is for absolute beginner's and can be considered as First step in learning MVC. In this article i am going to create a sample project to explain how the control flows between model-controller-view so as to build the basic foundation to create any MVC application.
Table of topics we are going to cover:
1. Folder Structure of MVC project.
2. Control flow of an MVC application.
3. Knowing and Creating Controllers, Models and Views.
So let us start by creating a simple project. The description of working of our project is given below .
Functionality of our Application:
1.When we run our application, it should contain a hyperlink on the home page named click. On clicking the hyperlink a message should be displayed i.e. Hello World!!
2. Then we will move a step forward. Instead of displaying a message we will display list of person names.
Understanding the folders Structure:
When you create a project a folder structure gets created by default under the name of your project which can be seen in solution explorer. Below i will give you a brief explanation of what these folders are for.
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 client 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.
Like As:
----------------------------------------------------------------------------------------------------------------------
Flow is as follows: 1->2->3->4
Let me first explain the flow of control for basic understanding. See the below diagram:
It first go to the controller then to model if required, from model back to controller and then to view and back to the controller. You will get more clear look of the flow of control and basig understanding of controllers , views and models as we move forward.
Moving Further :
Instead of displaying a message lets display list of person names. The process will the same as above. The only thing will change is that instead of passing message to the view we will pass list of names to the view.
Let us create another hyperlink on the HomePage for displaying List of Person. You now now how to create a hyperlink using ActionLink method and name it List_of_Person .
Here in actionName parameter of ActionLink method provide the name of action which will perform this task when the hyperlink is clicked , lets have a seperate action for this , name it ShowPerson.
Creating a Model :
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 :
Right click on Person folder in Views folder -->
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 ShowPerson view as
This article is for absolute beginner's and can be considered as First step in learning MVC. In this article i am going to create a sample project to explain how the control flows between model-controller-view so as to build the basic foundation to create any MVC application.
Table of topics we are going to cover:
1. Folder Structure of MVC project.
2. Control flow of an MVC application.
3. Knowing and Creating Controllers, Models and Views.
So let us start by creating a simple project. The description of working of our project is given below .
Functionality of our Application:
1.When we run our application, it should contain a hyperlink on the home page named click. On clicking the hyperlink a message should be displayed i.e. Hello World!!
2. Then we will move a step forward. Instead of displaying a message we will display list of person names.
Understanding the folders Structure:
When you create a project a folder structure gets created by default under the name of your project which can be seen in solution explorer. Below i will give you a brief explanation of what these folders are for.
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 client 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.
Like 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 = "Home", 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. Now how this id is used is explained further in the article.
Now for our application we will be needing a home page which will be opened when we run the application. This home page contains a hyperlink named click. As of now lets implement this much functionality.
If you remember the control flow diagram. The control first go to the controller. Thus for our application to run as desired we need a controller.
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. Now how this id is used is explained further in the article.
Now for our application we will be needing a home page which will be opened when we run the application. This home page contains a hyperlink named click. As of now lets implement this much functionality.
If you remember the control flow diagram. The control first go to the controller. Thus for our application to run as desired we need a controller.
Control Flow Structure :
Flow is as follows: 1->2->3->4
Let me first explain the flow of control for basic understanding. See the below diagram:
It first go to the controller then to model if required, from model back to controller and then to view and back to the controller. You will get more clear look of the flow of control and basig understanding of controllers , views and models as we move forward.
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 Sample.
Go to: File-->New-->Project.
On the left handside panel, in the Web section, select MVC 4 Web Application under .NET Framework 4.5 and name it Sample. 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.
Select the Razor engine as your View Engine. Now you might be wondering what a view engine is?
View Engine: In ASP.Net MVC, View engine is the one that works between your view and browser to provide valid HTML output to your browser by considering output provided by your view.
.NET Framework provides you two View Engines: Razor and ASPX. The basic difference between the two are listed below:
Namespace: Razor-> System.Web.Razor and ASPX-> System.Web.Mvc.WebFormViewEngine.
Extension: Razor has .cshtml (in C# and .vbhtml in VB) extension for views, layouts and partial views and ASPX views has .aspx extension for the views, .acsx for UserControls and .master for Master Pages.
Syntax: In Razor engine we use '@' to write the code and in ASPX engine we use delimiters starting with '<%' and ending with '%>' and writes code between them.
Now click OK, your appliction will be created.
We'll move step by step , for that we'll refer to the steps mentioned under the heading "Functionality of our application" .Now the read first step mentioned under that heading. It says :
"When we run our application, it should contain a hyperlink on the home page named click. On clicking the hyperlink a message should be displayed i.e. Hello World!!"
Thus, the very first thing we need is a homepage. Let us just focus on that part for now .
Now which of the three components ( Model , View , Controller ) we'll use to create our homepage?. Since a homepage will present something to the user using HTML elements.
If you remember the functions of each folder discussed above , you'll know that the correct component for homepage is View.
I have used Visual Studio 2013 but you can also work with Visual Studio 2012. In Visual Studio create a new project named Sample.
Go to: File-->New-->Project.
On the left handside panel, in the Web section, select MVC 4 Web Application under .NET Framework 4.5 and name it Sample. 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.
Select the Razor engine as your View Engine. Now you might be wondering what a view engine is?
View Engine: In ASP.Net MVC, View engine is the one that works between your view and browser to provide valid HTML output to your browser by considering output provided by your view.
.NET Framework provides you two View Engines: Razor and ASPX. The basic difference between the two are listed below:
Namespace: Razor-> System.Web.Razor and ASPX-> System.Web.Mvc.WebFormViewEngine.
Extension: Razor has .cshtml (in C# and .vbhtml in VB) extension for views, layouts and partial views and ASPX views has .aspx extension for the views, .acsx for UserControls and .master for Master Pages.
Syntax: In Razor engine we use '@' to write the code and in ASPX engine we use delimiters starting with '<%' and ending with '%>' and writes code between them.
Now click OK, your appliction will be created.
We'll move step by step , for that we'll refer to the steps mentioned under the heading "Functionality of our application" .Now the read first step mentioned under that heading. It says :
"When we run our application, it should contain a hyperlink on the home page named click. On clicking the hyperlink a message should be displayed i.e. Hello World!!"
Thus, the very first thing we need is a homepage. Let us just focus on that part for now .
Now which of the three components ( Model , View , Controller ) we'll use to create our homepage?. Since a homepage will present something to the user using HTML elements.
If you remember the functions of each folder discussed above , you'll know that the correct component for homepage is View.
Creating a View :
Add a new folder named Person in the views folder.Now Right click on the Person folder. Select Add option and then click on view in the expanded part of add option. Name it Home. Click ok. A view will be added in the Person folder such as Home.cshtml. Notice the extension. Remember in razor view engine the extension for view is .cshtml.
Now notice that in the view Home.cshtml there is by default code is created by the .Net Framework. Well, replace the <h2><\h2> HTML element with the following code :
Add a new folder named Person in the views folder.Now Right click on the Person folder. Select Add option and then click on view in the expanded part of add option. Name it Home. Click ok. A view will be added in the Person folder such as Home.cshtml. Notice the extension. Remember in razor view engine the extension for view is .cshtml.
Now notice that in the view Home.cshtml there is by default code is created by the .Net Framework. Well, replace the <h2><\h2> HTML element with the following code :
-----------------------------------------------------------------------------------------------------------------------
@Html.ActionLink("click","Message","Person")
-----------------------------------------------------------------------------------------------------------------------
This line of code creates a hyperlink named click . Notice the symbol '@'. Remember that in razor view engine it is used to write a line of code?.
'Html' is a helper class. This helper class is used to create html control such as textbox, label, hyperlink, etc. Thus to create a hyperlink the method used is ActionLink of Html helper class. There are total 10 overloads of ActionLink method. Here we have used the 4th overload i.e.
Html.ActionLink(string linkText, string actionName, string controllerName).
linkText is click.
actionName : Here provide the name of the action method that you want to get executed when the link is clicked. let us name it "Message"
controllerName : Here provide the name of the controller which contains the action method 'Message'. let us name it "Person" .
Note: There can be more than one controller containing same action names.
Now, This HTML component ( ActionLink ) will be rendered but won't work properly when clicked. The reason behind this is that we have not created the Controller and Action provided int the ActionLink method i.e. Person and Message respectively.
Now if you remeber that Controllers contains Actions. Thus here Person will contain Message. So let us create a controller first.
'Html' is a helper class. This helper class is used to create html control such as textbox, label, hyperlink, etc. Thus to create a hyperlink the method used is ActionLink of Html helper class. There are total 10 overloads of ActionLink method. Here we have used the 4th overload i.e.
Html.ActionLink(string linkText, string actionName, string controllerName).
linkText is click.
actionName : Here provide the name of the action method that you want to get executed when the link is clicked. let us name it "Message"
controllerName : Here provide the name of the controller which contains the action method 'Message'. let us name it "Person" .
Note: There can be more than one controller containing same action names.
Now, This HTML component ( ActionLink ) will be rendered but won't work properly when clicked. The reason behind this is that we have not created the Controller and Action provided int the ActionLink method i.e. Person and Message respectively.
Now if you remeber that Controllers contains Actions. Thus here Person will contain Message. So let us create a controller first.
Creating a Controller :
Go to the solution explorer, there right click on the Controller folder. Select the option Add and then click controller from the expanded part of the add option. Name it Person. Now while naming it remember that it must have word 'Controller' in the end. Thus the name of our controller will be PersonController. Click ok.
Notice that in the PersonController by default there will be some code. It contains a action(method) named index. Delete this method. Our PersonController have to contain Message action. Let us create that.
An action is a method in PersonController class. So inside PersonController class create an empty method named Message. For now just keep the return type of this method to be void.
Now we'll write the functionality of this action. We want Message (Action) to display a message i.e. Hello World!! . Thus to display this message we need a view. So we will return a view from the Message action. Now since we are returning something from Message action so its return type will not be void.
A view is a ViewResult class , which inherits ActionResult class. Thus the return type of Message action will be ActionResult.
So our PersonController with Message action will look like:
Go to the solution explorer, there right click on the Controller folder. Select the option Add and then click controller from the expanded part of the add option. Name it Person. Now while naming it remember that it must have word 'Controller' in the end. Thus the name of our controller will be PersonController. Click ok.
Notice that in the PersonController by default there will be some code. It contains a action(method) named index. Delete this method. Our PersonController have to contain Message action. Let us create that.
An action is a method in PersonController class. So inside PersonController class create an empty method named Message. For now just keep the return type of this method to be void.
Now we'll write the functionality of this action. We want Message (Action) to display a message i.e. Hello World!! . Thus to display this message we need a view. So we will return a view from the Message action. Now since we are returning something from Message action so its return type will not be void.
A view is a ViewResult class , which inherits ActionResult class. Thus the return type of Message action will be ActionResult.
So our PersonController with Message action will look like:
----------------------------------------------------------------------------------------------------------------------
class PersonController { public ActionResult Message() { return view(); } }
----------------------------------------------------------------------------------------------------------------------
The returntype of the Action may differ according to the need. For instance when returning a jason formatted content the returntype will be JasonResult. To return a view we use ActionResult.
This Message action will return a view named Message . Thus this view will contain the message "Hello World!!".
For this you have to create another view. The name of this view will be same as the action name returning it i.e. Message . Add this view in the same folder you've added the Home view i.e. in Person Folder.
Note : The name of the folder that we create in the views folder should be same as the controller name for which these views are added.
Thus to display the message Hello World we will use <h2></h2> heading HTML element. Just replace the content present between the <h2> HTML element with Hello World . Like this :
<h2>Hello World!!</h2>
Now apart from Message action we will need another action Home (let's say). Why Home action?
You know about the Message action : it is for displaying a message when the hyperlink is clicked. The other action Home : it is to display the homepage .
If you remember the control flow. It first goes to the controller and executes the actions in it , from where the control is directed to views and model (if required). However initially we have created a view for homepage containing hyperlink named click. We need that view to open as homepage when our application gets executed. This action can be implemented using actions of controller . Because that's what actions are for. Wink | ;)
Create another action in the similiar way we created Message action. Just name this action Home. It will have the same definition as of Message action. Only the difference is their name.
Now run your application press Ctrl + F5. You will see the following page :
This Message action will return a view named Message . Thus this view will contain the message "Hello World!!".
For this you have to create another view. The name of this view will be same as the action name returning it i.e. Message . Add this view in the same folder you've added the Home view i.e. in Person Folder.
Note : The name of the folder that we create in the views folder should be same as the controller name for which these views are added.
Thus to display the message Hello World we will use <h2></h2> heading HTML element. Just replace the content present between the <h2> HTML element with Hello World . Like this :
<h2>Hello World!!</h2>
Now apart from Message action we will need another action Home (let's say). Why Home action?
You know about the Message action : it is for displaying a message when the hyperlink is clicked. The other action Home : it is to display the homepage .
If you remember the control flow. It first goes to the controller and executes the actions in it , from where the control is directed to views and model (if required). However initially we have created a view for homepage containing hyperlink named click. We need that view to open as homepage when our application gets executed. This action can be implemented using actions of controller . Because that's what actions are for. Wink | ;)
Create another action in the similiar way we created Message action. Just name this action Home. It will have the same definition as of Message action. Only the difference is their name.
Now run your application press Ctrl + F5. You will see the following page :
The reason behind this is our RouteConfig class. Now go to the RouteConfig class in the App_Start folder and notice that the default url has controller as Home and action as Index. In our project we dont have any controller named home or any action named Index. This url defined here is executed when our application runs. But we want our home page that we have created to be dispayed. In order to do that we have to do minor changes in our RouteConfig class. Set the controller to Person and action to Home.
Note: Here in controller we need not to provide "PersonController" as whole, the .Net framework appends the word Controller automatically after the controller name provided i.e. "Person", when we run our application
Thus this url takes the controll to PersonController in that to the action Home which contains a return statement.
Now you might be wondering how will the control know which view to return as we didn't provided any name of the view in the return statement.? Well, it does that by action name. That is why action and view name must be same inside a folder whose name must be same as the controller containing those actions.
That is why we put the views in a folder named Person (name of the controller). Had there been another controller using some other views we would have created another folder ( with the name of that controller ) for those views.
In our proejct we have created a folder Person in the views folder and in that Person folder we have view names Home, in correspondence to PersonController containing action Home.
Now execute the application. It will work as expected.
The flow of the application will be : PersonController -> Home action -> Home view -> click hyperlink -> PersonController -> Message action -> Message view.
Now there are another ways of displaying that message if you don't want to hardcode it in the view. This is where parameter passing to the action and the id part of the url in the RouteConfig class comes in to the picture.
Note: Here in controller we need not to provide "PersonController" as whole, the .Net framework appends the word Controller automatically after the controller name provided i.e. "Person", when we run our application
Thus this url takes the controll to PersonController in that to the action Home which contains a return statement.
Now you might be wondering how will the control know which view to return as we didn't provided any name of the view in the return statement.? Well, it does that by action name. That is why action and view name must be same inside a folder whose name must be same as the controller containing those actions.
That is why we put the views in a folder named Person (name of the controller). Had there been another controller using some other views we would have created another folder ( with the name of that controller ) for those views.
In our proejct we have created a folder Person in the views folder and in that Person folder we have view names Home, in correspondence to PersonController containing action Home.
Now execute the application. It will work as expected.
The flow of the application will be : PersonController -> Home action -> Home view -> click hyperlink -> PersonController -> Message action -> Message view.
Now there are another ways of displaying that message if you don't want to hardcode it in the view. This is where parameter passing to the action and the id part of the url in the RouteConfig class comes in to the picture.
Avoid harcoding message in the view :
To avoid hardcoding the message in the view :
1.) One way is to pass that message as an argument.
To avoid hardcoding the message in the view :
1.) One way is to pass that message as an argument.
----------------------------------------------------------------------------------------------------------------------
public ActionResult Message() { return view("Hello World!!");
}
-----------------------------------------------------------------------------------------------------------------------
2.) To pass that message as id in the url.
In the Home view pass the message as a parameter to ActionLink method:
-----------------------------------------------------------------------------------------------------------------------
2.) To pass that message as id in the url.
In the Home view pass the message as a parameter to ActionLink method:
-----------------------------------------------------------------------------------------------------------------------
@Html.ActionLink("click","Message","Person", new { id = "Hello World!!"});
-------------------------------------------------------------------------------
In the Person controller's action : Message , recieve that passed parameter from ActionLink method as an argument to Message action:
-----------------------------------------------------------------------------------------------------------------------
public ActionResult Message(string id) { return view(id); //pass the recieved message to view }
-----------------------------------------------------------------------------------------------------------------------
and in the view:
-----------------------------------------------------------------------------------------------------------------------
@model string
<h2>@Model</h2>
-----------------------------------------------------------------------------------------------------------------------
you can also load the page directly using url as : {controller}\{action}\{id} which is Person\Message\Hello World!!
If you want to use the name of the parameter other than id (say message). Then you first have to change that name in RouteConfig class, such as:
If you want to use the name of the parameter other than id (say message). Then you first have to change that name in RouteConfig class, such as:
-----------------------------------------------------------------------------------------------------------------------
defaults:new{controller = "Person", action = "Home",message= UrlParameter.Optional}
------------------------------------------------------------------------------------------------------------------------
Here, I want the message parameter to be optional. You can also provide value if you don't want that to be optional.
Moving Further :
Instead of displaying a message lets display list of person names. The process will the same as above. The only thing will change is that instead of passing message to the view we will pass list of names to the view.
Let us create another hyperlink on the HomePage for displaying List of Person. You now now how to create a hyperlink using ActionLink method and name it List_of_Person .
Here in actionName parameter of ActionLink method provide the name of action which will perform this task when the hyperlink is clicked , lets have a seperate action for this , name it ShowPerson.
------------------------------------------------------------------------------------------------------------------------
defaults:new{controller ="Person",action = "Home", message= UrlParameter.Optional}
------------------------------------------------------------------------------------------------------------------------
Therefore , when the List_of_Person link is clicked it will execute the ShowPerson action of PersonController.
Now for list of person names we will need a class Person ( following the object oriented approach ) . This class will provide data (list of names i.e. list of Person object ) to the view. Remeber the class that are used to provide data are Models. So Person class will be our Model.
The flow will be from Controller -> Model (if required) -> back to Controller -> View -> Controller
Previously Model class were not neede but in this case Model will be required to provide tha data (list of person) to the view.
Lets go ahead and create a model class named as Person which will have two properties : FirstName and LastName.
Now for list of person names we will need a class Person ( following the object oriented approach ) . This class will provide data (list of names i.e. list of Person object ) to the view. Remeber the class that are used to provide data are Models. So Person class will be our Model.
The flow will be from Controller -> Model (if required) -> back to Controller -> View -> Controller
Previously Model class were not neede but in this case Model will be required to provide tha data (list of person) to the view.
Lets go ahead and create a model class named as Person which will have two properties : FirstName and LastName.
Creating a Model :
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; } }
--------------------------------------------------------------------------------
As our motive is to populate the view with the list of Person. So we will create a List of Person object and provide some values to its properties i.e. FirstName and LastName. And further we will supply this List to the view.
----------------------------------------------------------------------------------------------------------------------
public ActionResult ShowPerson() { List<person> persons = new List<person>() { new Person { FirstName = "Sherlock", LastName = "Holmes" }, new Person { FirstName = "James", LastName = "Watson" } }; return view(persons); }</person></person>
--------------------------------------------------------------------------------
If you remeber that a view returned by action will have the same name as of the action that returned it. In this case it will be ShowPerson. Since we have not created any view named ShowPerson yet. Lets create one.
Right click on Person folder in Views folder -->
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 ShowPerson view as
-----------------------------------------------------------------------------------------------------------------------
@model IEnumerable<CodeProject.Models.Person> @{ ViewBag.Title = "ShowPerson"; } <h2>ShowPerson</h2> <table> <tr> <th> @Html.DisplayNameFor(model => model.FirstName) </th> <th> @Html.DisplayNameFor(model => model.LastName) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.FirstName) </td> <td> @Html.DisplayFor(modelItem => item.LastName) </td> </tr> } </table>
------------------------------------------------------------------------------
Now run your application by pressing Ctrl+F5.
No comments:
Post a Comment