Adding A Controller

5 (6 votes)

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.

 

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 42554

5 Comments

- gjuro

sentence Run the application and browse to local_host:XXX_HelloWorld_Welcome_Mike_3

is missing the H-T-T-P part :-)

- Mike

@gjuro

Thanks. I've updated the article.

- Oscar

You should put something like "Next part of the guide , click here" link in the bottom of the page. Nice tutorial btw.

- ransems

Love the article. I dislike that the world thinks c# articles are the way to go. Love the VB, keep up the great work.

- Whitney W.

I am really new to everything and just started programming. I really need help in my project since I am not really a fan of coding. We are using MVC ASP with VB and even a single bit I am having difficulty understand. Do you have a tutorial for dummy beginners explaining how and why we do those codings. What are their functions and how they work in VB please thank you ... You will save me a lot of burden. I just really need to understand. Thank you so so so much and hoping for a reply soon.

Recent Comments

Pam 30/08/2017 11:30
In response to Sending Email in Razor Pages
Mike, RazorPages sound like a nice choice for somebody still working in ASP classic who wants to to...

Robby Robson 15/08/2017 00:43
In response to Routing in Razor Pages
Mike: great stuff. Now that .Core Standard 2.0 is formally out, how soon will you rewrite your book...

Satyabrata Mohapatra 28/07/2017 08:59
In response to Sending Email in Razor Pages
Bit off topic, but congratulation sir for your MVP award. You deserve it !!!...

Satyabrata Mohapatra 23/07/2017 16:43
In response to Razor Pages - The Elevator Pitch
@Dale Severin You can continue to build apps using asp.net web pages....

Satyabrata Mohapatra 23/07/2017 16:40
In response to Sending Email in Razor Pages
Thanks for sharing...learned a lot...

Gfw 22/07/2017 11:53
In response to Sending Email in Razor Pages
Question... Does System.Net.Mail support SSL?...

Dale Severin 20/07/2017 03:38
In response to Razor Pages - The Elevator Pitch
I work with razor web pages extensively. I appreciate the rapid development it permits me to I am as...

Obinna Okafor 14/07/2017 01:19
In response to Routing in Razor Pages
Thank you, Mike. Good post....

Satyabrata Mohapatra 11/07/2017 16:02
In response to Routing in Razor Pages
Very powerful routing system!!...

Cyrus 05/07/2017 03:41
In response to Razor Pages - Getting Started With The Preview
How can I trim packages and services as much as possible to use just razor pages? I don’t want to to...