Download presentation
Presentation is loading. Please wait.
Published byNora Shields Modified over 9 years ago
1
Introduction to MVC 4 02. Controllers NTPCUG Tom Perkins, Ph.D.
2
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
3
Add a Controller Right-click the Controllers folder Select Add Controller
5
Name the Controller Name Leave alone Click
6
New file created (HelloWorldController.cs) New File Created
7
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..."; } }
8
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
9
Browser results Index (default) Method returns a string
10
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
11
Now, Browse to: http://localhost:xxxx/HelloWorld/Welcome We haven’t used Parameters yet
12
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
13
Change Welcome Method public string Welcome(string name, int numTimes = 1) { return HttpUtility.HtmlEncode("Hello " + name + ", NumTimes is: " + numTimes); }
14
Use this address in the browser: http://localhost:xxxx/HelloWorld/Welcome?name=Scott&numtimes=4)
15
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 …
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.