Controller

Scaffolding

Scaffolding generates code for controllers and views based on an application's models.

Built with common ASP.NET Scaffolding system.

Available for MVC, WebAPI, and WebForms.

Screenshot of the Add Scaffolding dialog box. 

By adding a new controller, Visual Studio uses scaffolding to create new Razor views of the model the controller was created for.

 Screenshot of Visual Studios Solution Explorer with the new controller file and the new View files circled in blue.

Adding Actions

Controllers are classes

Actions are methods

Creating an action involves adding a method to a class.

  • Return Types
    • ActionResult
      • FileResult
      • JsonResult
      • ViewResult (returns a View)
  • Parameters
    • Normal parameters
    • MVC model binding
      • Uses HTTP get (retrieve form) and post (submit data in form)
Example of MVC model binding.
Image shows the two methods used to create a new Album. 1st display form using http get method, 2nd submit data from form using http post method.
Screen capture of annotated controller code.

Default model binder

<input type="text" name="Album.LinerNotes" />

The HTML id attribute is used for client-side scripting.

The HTML name attribute is used when sending to the server.

The default model binder automatically binds to all properties in the model. This can allow hackers to substitute for properties even if they are not displayed in the view. Here are the solutions to this problem:

model binding solutions.

The "Simplest" method shows the use of the Bind attribute being used in the Edit() method of the controller.

Data Context

Adding Validation

  • Attributes
    • Required
    • StringLength
      • MinLength
      • MaxLength
    • RegularExpression
    • Range
  • Error Message
    • {0} will use the display name
      • {0} must be provided

Filters

Security Filters

  • Authorize
    • Control who can access a controller/action
    • Properties
      • Users
      • Roles
  • ValidateAntiForgeryToken
    • Defends against cross-site request forgery
    • Requires anti-forgery token to be added to view
  • RequireHttps
    • Requires SSL
Adding an Authorize attribute to a controller action.
Adding an Authorize attribute to a controller action.
Adding an Authorize attribute to a controller action.
Adding a role-based Authorize attribute to a controller action.

Vanity URLs

example: www.mymusicstore.com/Album/Cure/Disintegration

  • Vanity URLs are handled by routing
  • Routing in MVC controls what controller/action is called based on the URL provided
  • Methods for updating routing:
    • RouteConfig.cs (in App_Start folder)
    • AttributeRouting

Controller Design Guidelines