ASP .Net MVC Lab Handout

In this Lab you will learn following:

 Creating the ASP .Net MVC application

 Creating a route for MVC application

 Creating a Controller

 Creating a View

 Creating a Model

 Developing a sample MVC Application Contents Application Requirements

For this lab you will need following application installed on your computer.

 Visual Studio 2012

 MVC 4

Create a MVC Project

1. Start Visual Studio and create a new Project (File -> New -> Project).

2. Under Visual C#, click on Web and select ASP .Net MVC4 Web application, Type BankDepositWithdrawal as the project name, and click OK as shown in the following figure:

On the next window, select Empty Template. Note that the View engine is set to Razor. Keep this setting and click the OK button. Visual Studio will create an empty Model, View and Controller folders in Solution Explorer as shown in the following figure:

In the above figure, you should recognize many elements. The purpose of the Global.asax, Web.config, and App_Data folders are the same as you have seen before. The folders named Controllers, Models, and Views are used to store the controllers, models, and views that make up your application.

Setup the Route

The ASP.NET Routing module is responsible for mapping incoming browser requests to particular MVC controller actions. In this part of the exercise you will verify that the routing has been setup correctly. Routing is setup in two places:

 Routing is enabled in the application’s Web.config file in the sections system.web.httpModules, systemweb.httpHandlers, system.webserver.modules, and system.webserver.handlers.

 The Global.asax file contains event handlers for an application’s page lifecycle events. A route table is created in the Global.asax file. By calling the following statement in the Application_Start method, the route table is initialized.

When an ASP.NET MVC application is run, the Application_Start() method is automatically called. This method, in turn, calls the RegisterRoute() method to create the route table. Initially, the route table contains a single route named default.

1. Open the file RouteConfig.cs file which appears in the App_Start folder in the Solution Explorer.

Inside the RegisterRoutes function, make sure we have route named routes. MapRoute as shown below. Which has three properties name, url, and defaults. Under the defaults we have mentioned controller named “Home” which has action called “Index” for this route.

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

Take a close look at the above route:  The name of the route is Default which is defined in the first argument.

 The second argument contains the URL and parameters.

 The third argument contains the parameter defaults.

Using the above route, suppose that you entered the URL /home/Index/3

 The controller is Home.

 The action is Index

 The id is 3.

Routes map to controller functions. Thus, the above URL would cause the following controller function to be executed:

HomeController.Index(3)

Routing Examples The following table shows several routing examples

Route Definition URL Example {controller}/{action}/{id} /Products/show/beverages blog/{action}/{entry} /blog/show/123 {reporttype}/{year}/{month}/{day} /sales/2008/1/5

Adding the Controller

1. Now you will setup the Controller. Right-click on the Controllers folder in Solution Explorer, Select Add and click Controller as shown below. 2. Set the controller name as HomeController, Keep Template as Empty MVC Controller, and Click the Add button to create the controller.

3. Open HomeController.cs file under Controllers folder in the Solution Explorer. In this file make sure we have Action named index as shown below. public ActionResult Index() { return View(); } Note that the Action is named Index. This value corresponds to the action name define in the route. Remember that routes are used to define the mapping to controller functions.

Adding the View Next, you will add the view. It is the view that is responsible for rendering HTML in a browser. By default the view can be created in two ways:

 You can use ASP.NET Web forms.

 More likely, you will use Razor, which is (and new) ASP.NET rendering engine. It looks much like PHP

1. Right click on the Index() action in the file HomeController.cs, and click on Add View as shown in the following figure: 2. Keep the view name as Index, View Engine as Razor and Click on the Add button.

This will create a file named Index.cshtml in the folder Views\Home in Solution Explorer.

Examine the Index.cshtml file that was just generated:  The @{} syntax tells the system to execute the contents on the server. Everything else is raw HTML.

 The ViewBag is used to maintain data when moving from controller to view.

 The ViewBag is also used to pass data from the controller to the corresponding view.

Adding the Model The model contains the business logic for an MVC application.

1. Right-click on Models folder in the Solution Explorer. Select Add and then select New Item.

2. Click on Code under Visual C# and select the Class type.

3. Name it as HomeModel.cs and click on the Add button as shown below. The following code is generated for you. This is just a class. However, its properties and methods are not called by your code. Rather they are called by the MVC infrastructure itself as you will see in a moment

Develop a Bank Deposit Application (MODEL) Now you will create the code for the model. This code implements simple bank account deposit functionality as follows:

 The properties named DepositAmount, AccountBalance, and Message are used by the control to read and write the various values.

 The Deposit method updates the account balance.

You will see how these methods are called by the controller in a moment. 1. Create the DepositAmount, AccountBalance and Message properties in the class named HomeModel (in the file HomeModel.cs)

2. Create the Deposit method as follows.

3. Make sure to add the reference to the System.ComponentModel.DataAnnotations namespace.

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace BankDepositWithdrawal.Models { public class HomeModel { [Required(ErrorMessage="Required")] public float DepositAmount { get; set; }

public float AccountBalance { get; set; }

public string Message { get; set; }

public HomeModel() { AccountBalance = 0.0F; }

public float Deposit(float DepositAmount) { return AccountBalance = AccountBalance + DepositAmount; } } }

Develop a Bank Deposit Application (Controller)

In this section, you will develop the code for the controller. The following points are relevant to the controller code:  The first time the page is displayed, it is displayed based on the user’s request (an HTTP GET). The code create an instance of the model, sets the message, and returns the model. This return the View passing the initialized model, which contains the data (message).

 By returning the View, the infrastructure will initialize the view (Web Page). You will create the view in a moment.

 When the Web Page is submitted (via a POST request), the second controller method is called to process the request. This code should appear straightforward. Note that statement like the following are referencing the model’s properties and calling the model’s methods.

In the Controllers\HomeController.cs file create 2 ActionRequests for Index. One is an HttpGet and another is HttpPost. In the HttpPost Index ActionRequest we verify that form has been filled correctly using ModelState.IsValid option. And if form data is correct the Deposit function from Model class will be executed. For this lab we are saving data in session. Create the following code in HomeController.cs file. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using BankDepositWithdrawal.Models; namespace BankDepositWithdrawal.Controllers { public class HomeController : Controller { [HttpGet] public ActionResult Index() { var model = new HomeModel(); model.Message = "Please Enter the Deposit Amount.";

return View(model); }

[HttpPost] public ActionResult Index(HomeModel model) { if (ModelState.IsValid) { if (Session["AccountBalance"] == null) { model.AccountBalance = 0.0F; } else { model.AccountBalance = (float)Session["AccountBalance"]; }

Session["AccountBalance"] = model.Deposit(model.DepositAmount);

model.Message = "Deposit was successful! Your Account balance is " + model.AccountBalance.ToString(); } else { model.Message = "Your Account balance is " + model.AccountBalance.ToString();

} return View(model); }

} }

Creating the Model In the final part of the lab, you will finish creating the model. Remember that this is Razor code.

 The @Model keyword defines the class that contains the model that will be used. In this case, this is the HomeModel class.

 The Html.BeginForm() method is an extension that triggers the Razord engine to generate a form.

 The following statement is another extension method. There are extension methods for all HTML controls. Here, we use only the Label, TextBox, and ValidationMessage. These extension methods accept two arguments, the name of the model and the applicable value

1. Open the Index.cshtml file under Views\Home folder in Solution Explorer. Htmlform is created in View. For the DepositAmount textbox entry validator is also added. Create the following code in Index.cshtml file.

@model BankDepositWithdrawal.Models.HomeModel @{ ViewBag.Title = "Bank Deposit Withdrawal"; }

@Model.Message

@using (Html.BeginForm()) { @Html.LabelFor(model => model.DepositAmount);
@Html.TextBoxFor(model => model.DepositAmount);
@Html.ValidationMessageFor(model => model.DepositAmount);

}

Testing the Application

1. Now, click on Start Debugging under Debug Menu as shown below.

1. Now on the internet browser you should see “Bank Deposit Application”, which was developed using ASP .Net MVC. Develop a Bank withdrawal application using ASP .Net MVC

Now it’s your turn to try some of this on your own.

Similar to the Bank Deposit Application create a Bank Withdrawal Application. Follow the above steps to create the ASP .Net MVC Bank Application, but instead of Deposit function logic, Develop the Withdrawal function.