Friday, March 21, 2014

MVC Tutorial Part 4 : Create View

In this demo we will be learning :
  1. How to create a View
  2. Displaying text on screen using View
  3. Call different Views associated to a Controller

Lets start by launching VS for web, we will be working on Demo2 project we created in Part 3.

Your EmployeeController.cs file must be as below:


Modify the string Index() Action method to an ActionResult. ActionResult is an abstract class that can have several subtypes. Change EmployeeController.cs controller code to below.

ActionResult is an abstract class that can have several subtypes.
ActionResult Subtypes
·         ViewResult - Renders a specified view to the response stream
·         PartialViewResult - Renders a specified partial view to the response stream
·         EmptyResult - An empty response is returned
·         RedirectResult - Performs an HTTP redirection to a specified URL
·         RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
·         JsonResult - Serializes a given ViewData object to JSON format
·         JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
·         ContentResult - Writes content to the response stream without requiring a view
·         FileContentResult - Returns a file to the client
·         FileStreamResult - Returns a file to the client, which is provided by a Stream
·         FilePathResult - Returns a file to the client

To add View right click on Index() method and navigate to Add View.

This will open an Add View window, without changing anything click on Add, we will learn about all other options inside the Add View window in later sessions.

This will create a View called Index.aspx inside Folder Views/Employee folder. Below is what is created.

Make changes to the newly added View as below:
<h4>Index.aspx View inside Employee Controller is called</h4>

Run application and navigate to, localhost:*****/Employee


So, now we are able to display content using View. Our EmployeeController is calling Index View here. If you modify URL as http://localhost:*****/Employee/Index it will display the same page.

Let’s now modify Employee controller as below and try adding some more Views.
Add below ActionsResults to your Employee Controller.
 public ActionResult Create()
        {
            return View();
        }

        public ActionResult Update()
        {
            return View();
        }

        public ActionResult Delete()
        {
            return View();
        }   
Page will look as below:

Now let’s add View for the ActionResults we have just added.
Right click on Create() Action method and navigate to Add View, Click Add. In the same manner add View for Delete() and Update().


Your Solution Explorer should look as below. Your Controller is now using four Views now, Create, Update, Delete and Index.
Navigate by changing your URL to below:

In next tutorial we will learn how to navigate between Views directly by using links, also navigate between different Views across different Controllers.




















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






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