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.
By adding a new controller, Visual Studio uses scaffolding to create new Razor views of the model the controller was created for.
Adding Actions
Controllers are classes
Actions are methods
Creating an action involves adding a method to a class.
Action Signature
- 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)
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:
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
- RegularExpression
- Range
- Error Message
- {0} will use the display name
Filters
Security Filters
-
Authorize
- Control who can access a controller/action
- Properties
-
ValidateAntiForgeryToken
- Defends against cross-site request forgery
- Requires anti-forgery token to be added to view
-
RequireHttps
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