Introduction to MVC 4 02. Controllers

Download Report

Transcript Introduction to MVC 4 02. Controllers

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
– 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;
Replace the contents
of the file:
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...";
}
}
}
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]
Name of Controller
class to execute
Action
(Method) to
execute
Any parameters
required for
executed method
Example had no Action name (index is the default)
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, 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:
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 …