Friday, February 28, 2014

MVC Tutorial Part 3 : Create Controller


In this demo we will be learning :

     1.      How to create a controller
     2.      Displaying text on screen
     3.      Overview of URL redirecting in MVC for Contoller


Lets start by launching VS for web, we will name this project as Demo2.

we will be making use of “Internet Application” and “ASPX” as our view engine.


This will create Demo2 project as below: 


Now, we will be adding a new Controller. For this, right click on Controller folder in Solution Explorer and navigate to Add >> Controller and click on Controller this will open Add Controller window.



Rename this Contoller as EmployeeController.
Note : All controller should be ending with name Controller. To know why read :

Do not select any Template, we will learn how to make use of templates later. Just click Add. This will add a new Controller inside Controller folder with name EmployeeController.cs also VS will open the file up for you.


Explanation of controller code :
Public ActionResult Index()
{
}

This is a declaration of method named Index(), which is declared inside a Controller, more than one method can be declared inside a controller and any method which is declared inside a controller can also be called action method.
Now, delete the ActionRestult method in code and add below String method to the code.

public string HrDepartment()
        {
            return "Employee in HR Department is Called";
        }

        public string PayrollDepartment()
        {
            return "Employee in Payroll Department is Called";
        }

Page will look as below :


Explanation of Code :
 public string HrDepartment()
        {
            return "Employee in HR Department is Called";
        }

Here HrDepartment() is our ActionMethod in Controller Employee & it will return a string.
Now lets run the application, you will get default application screen. Now to access and get values from the controller we need to change the URL in address bar of the browser.
Let’s change it to :

So, now to print the next set of output change URL to http://localhost:*****/Employee/PayrollDepartment

So, we are now able to display values on screen without using View. Controller can be used to display text sentences on the screen. But, to make a fullfledge web page design you require View.

Now lets understand how URL concept work. (URL redirections plays a major part in MVC, There will be detailed chapter later on URL concept and its working)

To understand this better now lets run our application and redirect to http://localhost:*****/Employee this will give an Error page. This is because we don’t have an Index() method declared in our Controller. Index method works as a default method for a controller, and even when we don’t make use of action name in URL it redirects to Index method if its declared in our controller.

Declare a Action Method Index() in our Employee Controller.
       
        public string Index()
        {
return "Index Method is called, Index method works as an Default action for a    controller";
        }
Your Employee controller will look as below:


Run the project and redirect to http://localhost:*****/Employee again. This time MVC will rediect to Index actionmethod inside Employee Controller. Which shows Index works as an default actionmethod for an Controller. 


So now if you look at Home page URL its states only localhost:*****, lets know how and where is this setup.


This page is coming from Home Controller and Index Action. Even if you extend your URL to localhost:*****/Home/Index, it will take you to the same page.

So, how is MVC handling this short URL, this is called URL Rewriting. URL rewriting hides page name and other details from end user.

In MVC 4.0 it is done making use of Global.ascx.cs and RouteConfig.cs files. In Solution Explorer you will find Global.ascx file, it has its code behind file called Global.ascx.cs, when you open this file you will find below lines in Application_Start() method. (Application start method is the method which is called when application load)

Line No: 23
RouteConfig.RegisterRoutes(RouteTable.Routes); 

Right Click on RegisterRoute and navigate to “Go to Definition”, it will take us to RouteConfig.cs which is located inside folder App_Start, this is where our URL rewriting is done. 



Now let’s understand the code in RouteConfig.cs

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

Line No 14:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

Above line will not allow user to get any file ending with .axd in your Solution. As the name suggests IgnoreRoute suggests that no one should be able to access any file with extension .axd, in the same way we can hide other files like .pdf, .jpg, etc.

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

Whenever a call is made by browser, a call is made to MapRoute to check what redirects are in place.
Here, url: "{controller}/{action}/{id}",  defines the sequence of invocation of the URL. I.e. in the URL Controller should be called first, then action later to it id.

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
This defines which default file to call and which action to invoke. Here id is optional, because of which even when we are not passing it in URL its working fine and taking us to Home/Index.


We will be learning creation of Views in next chapter









To learn more about MVC follow all parts of this tutorial series.
For detailed documentation and Video notes on MVC visit:
Created by:
Team: Techies@its4u
ITSolution4U – Technology Expert
ITSolution4U Home Page:
http://www.itsolution4u.com
Blogs:           http://techiesits4u.blogspot.in/
Twitter:     https://twitter.com/IT_S4U




Thursday, February 27, 2014

MVC Tutorial Part 2 : Understanding Default MVC Project


Now when we are done with basics of MVC, most of which is already present on internet from where you can get more details. Let’s start with creation of an MVC project.

.Net MVC provides an inbuilt project which contains basic template.

In this session we will be going through this inbuilt MVC application given to us by MVC.

In this session we will be learning :

  1.  Basic structure of MVC project.
  2.  How to run the project.

Assumptions before going forward:

Microsoft .NET Framework 4.5:
We are assuming that you have already installed latest .net version
Recommended: Microsoft ASP .NET Framework 4.5
To download .NET Framework 4.5 follow below link

Microsoft Visual Studio Express 2012 for web:
We are assuming that you have already installed latest Visual studio
Recommended: Microsoft Visual Studio Express 2012 for web
To download the Microsoft Visual Studio Express 2012 for web follow below link

Microsoft SQL Express 2012
SQL is not needed for this demo, but we would require this in coming demos.
To download MS SQL Express 2012 follow the link below

Once all installations are done. Go to Start >> All Programs >> Microsoft Visual Studio 2012 Express >> VS Express for Web

Click on VS Express for Web. This will open launch Visual Studio.


Now go to File and navigate to “New Project”. This will open a new project window. Name your project “Demo1” and select a location where you want your project to be saved. Go to Visual C# and select ASP.NET MVC 4 Web Application and click on OK.


Note: We will be doing all our demos in MVC 4.

This will open a window as below,
Currently we are interested in “Internet Application”, select “Internet Application”.
Exactly below select template window we have an option to select View Engine.
There are two types of view engines in MVC4.0 ASPX and Razor. Mostly widely used view engine is Razor but for our starting projects we will be using ASPX view engine. Once done click OK.


This will create a new MVC application for us. 

In Solution Explorer you can see multiple folders and files.
These are default folders and files which MVC has created for us. Now let’s go through some of the important features MVC has provided us.


In Solution explorer, the main folders which we will be going through are: Controller, View, Model, App_Start.   

As the name suggests MVC (Model View Controller), you can make out what each folder would contain.

Controller Folder : Controller folder would contains the controller. Controller is the part to which View and Model talks to.
The role of controller is to dictate what to do behind the scenes and what to display in the view next.

1. Controller receives a request
2. Controller decides the requested activities based on request parameters
3. Controller delegates tasks to be performed based on the request parameters
4. Controller delegates the next view to be shown

In our application MVC has created two controllers for us :
  • ·         Home Controller
  • ·         Account Controller

To understand them better lets run our application by pressing F5 or by using the Run button on VS screen. This will load a well structured web page as below.


Now if you go back to VS and open HomeController.cs file. You will find on line 13:

 ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

It’s the same message in title which is getting displayed on the Home screen above. This message is getting displayed in View called Index. If it’s not clear we will be going through all concepts in coming demos.


View Folder : View Folder contains sub folders as Account, Home, and Shared.


Home Folder: Files in this folder are called views. So the folder structure defines that Home Controller has three Views as About.aspx, Contanct.aspx and Index.aspx.


If you check line 11, 18 and 25 in HomeController.cs file, which shows we are calling these views from the Home Controller. Index.aspx is the default view.

Open Index.aspx file and go through the asp tags which MVC has created for us, you will find it similar to the text which is getting displayed on our home page after you run the project.



Model Folder: This folder currently has only one file. We don’t be using any model in some starting demos. To see model in a working you need to run the project and navigate to register page. Add some user name, password and click on Register. 
You will get error message as below, this validation message is coming from line 80 in AccountModels.cs Model.


App_Start Folder :
This folder contains some startup files. Some important files are explained below.
·         
     AuthConfig.cs: The AuthConfig file contains code to register clients for external authentication providers. By default, this code is commented out, so none of the external providers are enabled.
·         RouteConfig.cs: It is used to do URL routing or rewriting. (To know more about URL routing in asp.net : http://msdn.microsoft.com/en-us/library/cc668201.aspx )

We will be creating a small project in our next demo.



To learn more about MVC follow all parts of this tutorial series.
For detailed documentation and Video notes on MVC visit:


Created by:

Team: Techies@its4u
ITSolution4U – Technology Expert
ITSolution4U Home Page:
http://www.itsolution4u.com
Twitter:     https://twitter.com/IT_S4U
                                 




Wednesday, February 26, 2014

MVC Tutorial Part 1 : What is MVC?


MVC (Model View Controller) is a software pattern for implementing user interfaces.

It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user.

[Software Pattern: Software patterns are well tested and proven development practice or technique which helps in development of a good software product; you can also say it as a template which can be used again and again for all your projects. Some examples of Software patterns are Abstract factory, Factory method, Object pool, Singleton, etc. To learn what is a Software pattern read more on:  [ http://en.wikipedia.org/wiki/Software_design_pattern ]

To understand MVC it’s not necessary to learn or know Web forms. But if you are aware of 3-Tier Architecture which is used in web forms, it will facilitate you in understanding MVC structure better. Web form 3-Tier Architecture consists of Presentation layer or UI layer, Business layer and Data access layer. The Presentation layer is where the UI or front end is developed. The Business layer contains the business logic; by doing so we are hiding data from front end user and keep it isolated from external users and the last layer Data access layer is used for talking to the database. To learn more about 3 Tier Architecture you can refer:[http://www.codeproject.com/Tips/662107/Understand-3-Tier-Architecture-in-Csharp]

What does the 3 component of MVC i.e. Model View Controller defines?

Controller – Controller is the main component of MVC, which means it interacts with both Model and View.

A controller is the one to which user interacts, which further send and receive data from Model and View.  The Controller can send commands to the model to update the model’s state on the other hand it can also send commands to its associated View to change the Views presentation of the model.

Model – Model notifies its associated views and controllers when there has been a change in its state. This notification allows views to update their presentation, and the controllers to change the available set of commands.


View - view is told by the controller all the information it needs for generating an output representation to the user. It can also provide generic mechanisms to inform the controller of user input.

If you want more detailed document and diagram on MVC refer: http://ist.berkeley.edu/as-ag/pub/pdf/mvc-seminar.pdf





Now, let’s discuss benefits of using MVC in short:

  • ·         It gives more control over HTML
  • ·         No Code behind files
  • ·         Separation of Concern [i.e. UI will contain only UI code]
  • ·         Provides ease of testing
  • ·         Easy URL routing
  • ·         No Postback
  • ·         No ViewState

To know more about MVC advantages read through some blogs on: [http://forums.asp.net/t/1459417.aspx]


If it’s still not clear how MVC works, don’t worry you will get more clarity when you move forward with implementation and developing MVC examples practically.



To learn more about MVC follow all parts of this tutorial series.
For detailed documentation and Video notes on MVC visit:


Created by:

Team: Techies@its4u
ITSolution4U – Technology Expert
ITSolution4U Home Page: http://www.itsolution4u.com
Twitter:     https://twitter.com/IT_S4U
LinkedIn:   www.linkedin.com/company/itsolution4u