Monday, 25 May 2015

MVC 1st Program

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; }
 
}

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.

No comments:

Post a Comment