"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Creating an Action (VB)

by Microsoft

Learn how to add a new action to an ASP.NET MVC controller. Learn about the requirements for a method to be an action.

The goal of this tutorial is to explain how you can create a new controller action. You learn about the requirements of an action method. You also learn how to prevent a method from being exposed as an action.

Adding an Action to a Controller

You add a new action to a controller by adding a new method to the controller. For example, the controller in Listing 1 contains an action named Index() and an action named SayHello(). Both methods are exposed as actions.

Listing 1 - Controllers.vb

[!code-vbMain]

   1:  <HandleError()> _
   2:  Public Class HomeController
   3:      Inherits System.Web.Mvc.Controller
   4:   
   5:      Function Index() As ActionResult
   6:          Return View()
   7:      End Function
   8:   
   9:      Function SayHello() As String
  10:          Return "Hello!"
  11:      End Function
  12:  End Class

In order to be exposed to the universe as an action, a method must meet certain requirements:

Notice that there are no restrictions on the return type of a controller action. A controller action can return a string, a DateTime, an instance of the Random class, or void. The ASP.NET MVC framework will convert any return type that is not an action result into a string and render the string to the browser.

When you add any method that does not violate these requirements to a controller, the method is exposed as a controller action. Be careful here. A controller action can be invoked by anyone connected to the Internet. Do not, for example, create a DeleteMyWebsite() controller action.

Preventing a Public Method from Being Invoked

If you need to create a public method in a controller class and you don’t want to expose the method as a controller action then you can prevent the method from being invoked by using the <NonAction> attribute. For example, the controller in Listing 2 contains a public method named CompanySecrets() that is decorated with the <NonAction> attribute.

Listing 2 - Controllers.vb

[!code-vbMain]

   1:  Public Class WorkController
   2:      Inherits System.Web.Mvc.Controller
   3:   
   4:       _
   5:      Function CompanySecrets() As String
   6:          Return "This information is secret."
   7:      End Function
   8:   
   9:  End Class

If you attempt to invoke the CompanySecrets() controller action by typing /Work/CompanySecrets into the address bar of your browser then you’ll get the error message in Figure 1.

Invoking a NonAction method

Figure 01: Invoking a NonAction method(Click to view full-size image)

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/mvc/overview/older-versions-1/controllers-and-routing/creating-an-action-vb.htm
< THANKS ME>