Introduction to MVC Controllers NTPCUG Tom Perkins, Ph.D.
The MVC Pattern Models: – Classes that represent the data of the app – Validation logic – Business Rules Views: – Template files used to generate HTML responses Controllers: – Handle requests to app – Retrieve Model data – Specify View templates to generate HTML response to user
Add a Controller Right-click the Controllers folder Select Add Controller
Name the Controller Name Leave alone Click
New file created (HelloWorldController.cs) New File Created
Replace the contents of the file: using System.Web; using System.Web.Mvc; namespace MvcMovie.Controllers { public class HelloWorldController : Controller { // // // GET: /HelloWorld/ // GET: /HelloWorld/ public string Index() public string Index() { return "This is my default action..."; return "This is my default action..."; } // // // GET: /HelloWorld/Welcome/ // GET: /HelloWorld/Welcome/ public string Welcome() public string Welcome() { return "This is the Welcome action method..."; return "This is the Welcome action method..."; } }
Information about HelloWorldController Has two methods Each method returns a string of HTML Run the app (Press F5 or Ctrl+F5) Append “HelloWorld” to the path in the address bar
Browser results Index (default) Method returns a string
MVC Address Format The Controller class (and method) that gets invoked depends on the incoming URL. Default format expected: – /[Controller]/[ActionName]/[Parameters] Example had no Action name (index is the default) Name of Controller class to execute Action (Method) to execute Any parameters required for executed method
Now, Browse to: We haven’t used Parameters yet
Let’s use some parameters Change the Welcome method: public string Welcome(string name, int numTimes = 1) { return HttpUtility.HtmlEncode("Hello " + name + ", NumTimes is: " + numTimes); } 2 parameters: name, numTimes Note C# default to 1 for numtimes
Change Welcome Method public string Welcome(string name, int numTimes = 1) { return HttpUtility.HtmlEncode("Hello " + name + ", NumTimes is: " + numTimes); }
Use this address in the browser:
The examples thus far: The controller has been acting as both the V + C in the MVC app – both Controller and View Usually, we don’t want to return a string directly to the user Next – Let’s use a separate View template to return some HTML …