Waffle Recipes

How-To's and Tutorials for the ActiveWAFL Framework

How to Read HTTP Get/Post Variables in an MVC Controller Action

Posted Nov 21, 2014

ActiveWAFL controller actions all receive an instance of an HTTP Request object as an attribute.
This object provides methods for getting information about the request, including any GET/POST variables submitted via a form or the URL.

There are several strongly-typed methods for getting the request variables. These methods all begin with GetInput....
For example, there is GetInputInteger, GetInputString, GetInputBoolean, and so on.
There is one method, GetInputArray, for getting arrays of input, for example if you submit several form elements with the same name followed by square brackets. There is also a generic method named GetInput which does not validate the data type of the input.

Example of Reading Input in a Controller Action

Example HTML template with a form that has a few inputs
  1. <form action="MyController">
  2.     <label>Foo (an integer)</label>
  3.     <input type="number" min="0" max="100" name="Foo" />
  4.  
  5.     <label>Bars</label>
  6.     <input type="text" name="Bar[]" />
  7.     <input type="text" name="Bar[]" />
  8.     <input type="text" name="Bar[]" />
  9.  
  10.     <label>Your Email Address</label>
  11.     <input type="text" name="Email" />
  12. </form>
Example controller action that reads the passed in 'Foo' integer and 'Bar' email address variables.
  1. namespace MyApp\Controllers;
  2.  
  3. class MyController
  4. extends \DblEj\Mvc\ControllerBase
  5. {
  6.     public function DefaultAction(\DblEj\Communication\Http\Request $request, \DblEj\Application\IMvcWebApplication $app)
  7.     {
  8.         //read the value of the Foos from the request input, validating that its an integer
  9.         $foo = $request->GetInputInteger("Foo");
  10.  
  11.         //read the value of the Bars from the request input
  12.         $foo = $request->GetInputArray("Bar");
  13.  
  14.         //read the value of the Email variable from the request input, validating that it's an email address
  15.         $$email = $request->GetInputEmailAddress("Email");
  16.  
  17.         return $this->createResponseFromRequest($request, $app);
  18.     }
  19. }

Conclusion

The DblEj\Communications\Http\Request provides standard methods for accessing information about the request and makes dealing with HTTP inputs reliable and easy.