150 likes | 339 Views
Introduction to MVC 4 02. 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
E N D
Introduction to MVC 402. 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
using System.Web; using System.Web.Mvc; namespace MvcMovie.Controllers { public class HelloWorldController : Controller { // // GET: /HelloWorld/ public string Index() { return "This is my <b>default</b> action..."; } // // GET: /HelloWorld/Welcome/ public string Welcome() { return "This is the Welcome action method..."; } } } Replace the contents of the file:
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 • http://localhost:1234/HelloWorld
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) Action (Method) to execute Any parameters required for executed method Name of Controller class to execute
Now, Browse to:http://localhost:xxxx/HelloWorld/Welcome We haven’t used Parameters yet
Let’s use some parameters • Change the Welcome method: • public string Welcome(string name, intnumTimes = 1) • { • return HttpUtility.HtmlEncode("Hello " + name + ", NumTimes is: " + numTimes); • } • 2 parameters: name, numTimes • Note C# default to 1 for numtimes
Change Welcome Method publicstringWelcome(string name, intnumTimes = 1) { returnHttpUtility.HtmlEncode("Hello " + name + ", NumTimes is: " + numTimes); }
Use this address in the browser:http://localhost:xxxx/HelloWorld/Welcome?name=Scott&numtimes=4)
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 …