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 3
Create a MVC Project 3
Setup the Route 6
Routing Examples 7
Adding the Controller 7
Adding the View 9
Adding the Model 10
Develop a Bank Deposit Application (MODEL) 12
Develop a Bank Deposit Application (Controller) 13
Creating the Model 14
Testing the Application 15
Develop a Bank withdrawal application using ASP .Net MVC 17
Application Requirements
For this lab you will need following application installed on your computer.
· Visual Studio 2015
· MVC 5 (Installed as part of Visual Studio 2016.
Create a MVC Project
- Start Visual Studio and create a new Project (File -> New -> Project). Create an ASP.NET Web Application as you have been doing. Name the application. MVCCustomer.
- If you create and MVC application, the templates are complete but complicated. They contain login / about / and other pages. Here you will create an empty application so as to focus on MV itself.
Create an MVC application as shown in the following figure. This time, Create an empty application. Uncheck the box titled Host in the Cloud. Make sure that the MVC check box is checked so that .NET will create the appropriate folders. - Click OK to begin creating the application.
- You might see the following dialog box asking you to configure Microsoft Azure Services. If you do, click Cancel.
- Visual Studio will create several folders and templates as shown in the following figure. Note that this organization is very similar to the MVC Web API application already discussed.
In the above figure, you should recognize many elements.
· The purpose of the Global.asax file is to start the application. If you look that the file, you will see that the MvcApplication class derives from the System.Web.HttpApplication class instead of the System.Web.HttpApplication class. Other than that, you will see the both application types are very similar.
The Application_Start() method runs when the application begins. It contains the following statement to register the routes. This is similar to what you saw with the Web API.
RouteConfig.RegisterRoutes(RouteTable.Routes);
If you look at the method, you will also see that it contains other configuration routines. Only those we actually use will be discussed in the lab.
· If you look at the App_Start/RouteConfig.cs file, you will see that it configures the URL routes just as you saw before.
· The folder named Content contains template CSS files that are used throughout the application. This folder does not exist yet but will when you start adding views.
· The folder named Controllers contains the controllers as you have seen before. However, this template will have several controllers instead of just 1.
· As before, the folder named Models contains the classes that in define the data structures for the application.
· The folder named Views contains the views (user interface). You have not seen these files before. Views and Razor will be discussed in detail later in the lab.
· The Web.config, and App_Data folders are the same as you have seen before and have the same purpose.
Setup the Routes
When an ASP.NET MVC application is run, the Application_Start() method is automatically called. This method, in turn, calls the RegisterRoutes() method to create the route table. Initially, the route table contains a single route named default. Again, these are the same routes that you saw when you created the WebApi. Except here, there will ultimately be a Razor user interface (view)
- In the Solution Explorer, open the file RouteConfig.cs file which appears in the App_Start folder.
Inside the RegisterRoutes() function, there should be a “default route” which has three properties named name, url, and defaults. Under the defaults the controller is 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.
· The second argument contains the URL and parameters. There is a controller, with an action, and an ID.
· The third argument contains the parameter defaults. The default controller is home and the default action is index. The id parameter is optional
Using the above route, suppose that you entered the URL /Home.
· The controller is Home.
· The action is Index
· The id (parameter) is null.
As you have seen, routes map to controller functions. Thus, the above URL would cause the following controller function to be executed:
HomeController.Index()
In the next set of steps, you will add a second route to deal with Customers. This controller is a bit different. It has another element in the path name ({name})
- In the Solution Explorer, that the file RouteConfig.cs is open.
- Enter the following statements in the RegisterRoutes procedure. Enter the statements at the end of the procedure.
routes.MapRoute(
name: "Customer",
url: "{controller}/{action}/{name}/{id}"
);
Routing Examples
The following table shows a few routing examples:
{controller}/{action}/{id} / /Products/show/beverages
blog/{action}/{entry} / /blog/show/123
{reporttype}/{year}/{month}/{day} / /sales/2008/1/5
Adding the Controllers
In this lab, you will add two controllers. The first will end up operating as a home page. The second will display customers. This code to display customers is very similar to what you saw in the last lab.
- Now you will setup the first Controller. Right-click on the Controllers folder in Solution Explorer, Select Add and click Controller as shown below.
- Create an Empty MVC 5 Controller as shown in the following figure.
- Set the controller name as HomeController, Keep Template as Empty MVC Controller, and Click the Add button to create the controller.
- Open HomeController.cs file under Controllers folder in the Solution Explorer. In this file, make sure you create an Action named Index as shown below. Note that the Action returns a data type of string. You will need to modify the template code so that IndexReturns a string. You will modify this code later when you create the view.
namespace MVCCustomer.Controllers
{
public class HomeController : Controller
{
// GET: Home
public string Index()
{
return "Home Controller / <b>Index()</b>";
}
}
}
5. Now, create another controller named CustomersController.cs. Its code should look like the following:
namespace MVCCustomer.Controllers
{
public class CustomersController : Controller
{
// GET: Customers
public string Index()
{
return "Customers Controller / <b>Index()</b>";
}
}
}
- Now it’s time to run the application to see what you have been doing. Press F5 to run the program. You should see the following URL and content in the Web browser. Recall that the default rout is Home/Index so the system will call the HomeController and the procedure named index, which returns a string. That string is rendered in the browser>
- Now enter the following URL. You can see the CustomersController runs. The default procedure is again named index because of the Route
Adding the View
At this point, your program is pretty simple. It does not yet exploit the idea of MVC. You have handled the Controller, which now returns a string. And that string is rendered as HTML. 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 the newer ASP.NET rendering engine designed for MVC. It looks much like PHP. In this lab, you will see how to implement the later.
Take a look at the following controller code that replaces the preceding Controller code that you just wrote
namespace MVCCustomer.Controllers
{
public class CustomersController : Controller
{
// GET: Customers
public ActionResult Index()
{
return View();
}
}
}
First, note that the Index procedure has been modified so that it returns an ActionResult instead of a string. In addition, the View is returned.
One of the things that controllers return is a View having a data type of ActionResult. This is the view that you will create in a minute.
- Modify the Index() function on the HomeController.cs file as follows:
namespace MVCCustomer.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
}
- Right click on the Index() action (function) in the file HomeController.cs, and click on Add View as shown in the following figure:
- Keep the view name as Index, and Click on the Add button.
If you look at what has happened, the following files were created in the Views folder. And, as you will see, all of these views use Razor!
A file was created named Index.cshtml in the folder Views\Home in Solution Explorer. Another file named _Layout.cshtml was also created.
Examine the Index.cshtml file that was just generated. It contains the following:
· The @{} syntax tells the system to execute the contents on the server. It’s saying that the code is Razor code. Everything else is raw HTML.
· The ViewBag is used to maintain data when moving from controller to view. In the above example, the Title property is being set.
· The ViewBag is also used to pass data from the controller to the corresponding view.
1. Now, create a Csutomers view in the same way that you created the Home View.
2. Modify the Controllers/CustomersController.cs file as follows.
3. Proceed to create the view as you just did. But this time, name the View Customer:
4. When complete, the solution explorer should contain the following files:
Using Razor
So now things get interesting. If you look, you will see that .NET generated a file named _viewStart.cshtml and a file named _layout.cshtml.
The file named _viewStart.xshtml contains the following code.
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
All that it does is to load the file Views/Shared/_Layout.cshtml:
Most all of this should look familiar to you. It’s an HTML file that is rendered by Razor as a master file. The only thing interesting are the statements are the ones preceded by the @ character. Remember that the @ character marks the code as Server side Razor code.
· @ViewBag.Title reads the title from the ViwBag.
· @Html.ActionLink write an <a> tag. The url contains the correct route. You will modify this in a moment.
· @RenderBody() tells razor to render the actual view here.
Next, you will modify the global layout file so that it will display the two different views.
- Activate the _Layout.cshtml file in the Code Editor.
- Comment or remove the following line.
- Insert the above lines where indicated.
- Run the application. You should be able to navigate between the two views.
Adding the Model
The model contains the business logic and data for an MVC application.
- Right-click on Models folder in the Solution Explorer. Select Add and then select New Item.
- Click on Code under Visual C# and select the Class type.
- Name it as Customer.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
Creating the Model Code
Now you will create the code for the model. This code does nothing more than the code from the last demonstration. It creates the class named Customer.
· 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.
- Create the following properties in the class:
- Modify the Customers.Controller.cs file as follows:
- And finally enter the following in the Customer.cshtml file
model IEnumerableMVCBankDeposit.Models.Customer
@{
ViewBag.Title = "Welcome layout";
}
h2Welcome</h2
ul
@for (int i = 0; i < ViewBag.ID; i++)
{
age</li
}
</ul
table class="table">
tr
th
@Html.DisplayNameFor(model => model.Id)
</th
th
@Html.DisplayNameFor(model => model.Name)
</th
th
@Html.DisplayNameFor(model => model.Category)
</th
</tr
@foreach (var item in Model)
{
tr
td
@Html.DisplayFor(modelItem => item.Id)
</td
td
@Html.DisplayFor(modelItem => item.Name)
</td
td
@Html.DisplayFor(modelItem => item.Category)
</td
</tr
}
</table