Adding A Controller

This tutorial is the second in a series of a Visual Basic versions of the Introduction to ASP.NET MVC 5 tutorials published on the www.asp.net site. The original series, produced by Scott Guthrie (twitter @scottgu ), Scott Hanselman (twitter: @shanselman ), and Rick Anderson ( @RickAndMSFT ) was written using the C# language. My versions keep as close to the originals as possible, changing only the coding language. The narrative text is largely unchanged from the original and is used with permission from Microsoft.

This tutorial series will teach you the basics of building an ASP.NET MVC 5 Web application using Visual Studio 2013 and Visual Basic.  A Visual Studio Express For Web project with VB source code is available to accompany this series which you can download.

The tutorial series comprises 11 sections in total. They cover the basics of web development using the ASP.NET MVC framework and the Entity Framework for data access. They are intended to be followed sequentially as each section builds on the knowledge imparted in the previous sections. The navigation path through the series is as follows:

  1. Getting Started
  2. Adding a Controller
  3. Adding a View
  4. Adding a Model
  5. Creating a Connection String and Working with SQL Server LocalDB
  6. Accessing Your Model's Data from a Controller
  7. Examining the Edit Methods and Edit View
  8. Adding Search
  9. Adding a New Field
  10. Adding Validation
  11. Examining the Details and Delete Methods

2. Adding a Controller

MVC stands for model-view-controller.  MVC is a pattern for developing applications that are well architected, testable  and easy to maintain. MVC-based applications contain:

  • Models: Classes that represent the data of the application and that use validation logic to enforce business rules for that data.
  • Views: Template files that your application uses to dynamically generate HTML responses.
  • Controllers: Classes that handle incoming browser requests, retrieve model data, and then specify view templates that return a response to the browser.

We'll be covering all these concepts in this tutorial series and show you how  to use them to build an application.

Let's begin by creating a controller class. In Solution  Explorer, right-click the Controllers folder and then click Add, then Controller.

Adding a controller

In the Add Scaffold dialog box, click MVC 5  Controller - Empty, and then click Add.

Adding a controller

Name your new controller "HelloWorldController" and click Add.

Adding a controller

Notice in Solution  Explorer that a new file  has been created named HelloWorldController.vb and a new folder Views\HelloWorld. The controller is open in the IDE.

Adding a controller

Replace the contents of the file with the following code.

Imports System.Web.Mvc

Public Class HelloWorldController
    Inherits Controller

    ' GET: /HelloWorld
    Function Index() As String
        Return "This is my <b>default</b> action..."
    End Function

    'GET: /HelloWorld/Welcome/
    Function Welcome() As String
        Return "This is the Welcome action method..."
    End Function
End Class

The controller methods will return a string of HTML as an example. The controller is named HelloWorldController and  the first method is named Index.  Let’s invoke it from a browser. Run the application (press F5 or Ctrl+F5). In the  browser, append "HelloWorld" to the path in the address bar. (For example, in the illustration below, it's http://localhost:1804/HelloWorld.)  The page in the browser will look like the following screenshot. In the method above, the code returned a string directly. You told the system to just return some HTML, and it did! 

Adding a controller

ASP.NET MVC invokes different controller classes (and different action methods within  them) depending on the incoming URL. The default URL routing logic used by ASP.NET MVC uses a format like this to determine what code to invoke:

/[Controller]/[ActionName]/[Parameters]

You set the format for routing in the App_Start/RouteConfig.vb  file.

Public Module RouteConfig
    Public Sub RegisterRoutes(ByVal routes As RouteCollection)
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

        routes.MapRoute(
            name:="Default",
            url:="{controller}/{action}/{id}",
            defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional}
        )
    End Sub
End Module

The forward slash ( / ) is a segment delimiter. When you run the application and don't supply any URL segments, it defaults to the "Home" controller and the "Index" action method specified in the defaults section of the code above. 

The first segment in the URL determines the controller class to execute. So /HelloWorld maps  to the HelloWorldController class.  The second segment determines the action method on the class to execute.  So /HelloWorld/Index would cause the Index method of the HelloWorldController class to execute. Notice that we only had to browse to /HelloWorld and the Index method was used by default. This is because a method named Index is specified as the default method that will be called on a controller if one is not explicitly specified. The third segment of the URL (Parameters) is for route data. We'll see route data later on in this tutorial.

Browse to http://localhost:xxxx/HelloWorld/Welcome.  The Welcome method runs and returns the string "This is the Welcome action method...". The  default MVC mapping is /[Controller]/[ActionName]/[Parameters].  For this URL, the controller is HelloWorld and Welcome is the action method. You haven't used the [Parameters] part of the URL yet.

Adding a controller

Let's modify the example slightly so that you can pass some parameter information from the URL to the controller (for example, /HelloWorld/Welcome?name=Mike&numtimes=4).  Change your Welcome method  to include two parameters as shown below. Note that the code uses the VB optional parameter feature to indicate that the numTimes parameter should default to 1 if no value is passed for that parameter.

Function Welcome(name As String, Optional numTimes As Integer = 1) As String
    Return HttpUtility.HtmlEncode("Hello " & name & ", NumTimes is: " & numTimes)
End Function

Security Note: The code above uses HttpServerUtility.HtmlEncode to protect the application from malicious input (namely JavaScript).  For more information see How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings.

Run your application and browse to the example URL (http://localhost:xxxx/HelloWorld/Welcome?name=Mike&numtimes=4).  You can try different values for name and numtimes in  the URL. The ASP.NET MVC model binding system automatically maps the named parameters from the query string in the URL to parameters in your method.

Adding a controller

In the sample above, the URL segment (Parameters) is not used, the name and numTimes parameters are passed as query string values. The ? (question mark) in the above URL is a separator, and the query string follows. The & character separates name/value pairs within the query string.

Replace the Welcome method with the following code:

Function Welcome(name As String, Optional ID As Integer = 1) As String
    Return HttpUtility.HtmlEncode("Hello " & name & ", ID: " & ID)
End Function

Run the application and enter the following URL:  http://localhost:xxx/HelloWorld/Welcome/3?name=Mike

Adding a controller

This time the third URL segment contains a value (3) which is therefore matched to the route parameter ID. The Welcome action method contains a parameter (ID) that matched the URL specification in the RegisterRoutes method.

Public Module RouteConfig
    Public Sub RegisterRoutes(ByVal routes As RouteCollection)
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

        routes.MapRoute(
            name:="Default",
            url:="{controller}/{action}/{id}",
            defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional}
        )
    End Sub
End Module

In ASP.NET MVC applications, it's more typical to pass in parameters as route data (like we did with ID above) than passing them as query string values. You could also add a route to pass both the name and numtimes in  parameters as route data in the URL. In the App_Start\RouteConfig.vb  file, add the "Hello" route:

Public Module RouteConfig
    Public Sub RegisterRoutes(ByVal routes As RouteCollection)
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

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

        routes.MapRoute(
            name:="Hello",
            url:="{controller}/{action}/{name}/{id}"
        )
    End Sub
End Module

Run the application and browse to http://localhost:XXX/HelloWorld/Welcome/Mike/3.

Adding a controller

For many MVC applications, the default route works fine. You'll learn later in this tutorial series to pass data using the model binder, and you won't have to  modify the default route for that.

In these examples the controller has been doing both of the "V" and "C" portions of MVC — that is, the view and controller work. The controller is returning HTML directly. Ordinarily you don't want controllers returning HTML directly, since that becomes very cumbersome to code and manage. Instead we'll typically use a separate view template file to help generate the HTML response. The next section looks at how we can do this.