Routing, Controllers, Acti Ons, Views, Areas : Softuni Team
Routing, Controllers, Acti Ons, Views, Areas : Softuni Team
Routing, Controllers, Acti Ons, Views, Areas : Softuni Team
SoftUni Team
Technical Trainers
Software University
http://softuni.bg
Table of Contents
1. ASP.NET MVC Routing
Route constraints
3. Razor Views
Layout and sections
Helpers
Partial views
4. Areas 2
ASP.NET MVC Routing
ASP.NET MVC Routing
Mapping between patterns and a combination of
controller + action + parameters
4
Register routes
In Global.asax in the Application_Start() there is:
RouteConfig.RegisterRoutes(RouteTable.Routes);
RoutesConfig class is located in /App_Start/ in internet
applications template by default
Routes to ignore
The [*] means all left
Route name
Route pattern
Default parameters
5
Routing Examples
http://localhost/Products/ById/3
Controller: Products
Action: ById
Id: 3 6
Routing Examples (2)
http://localhost/Products/ById
Controller: Products
Action: ById
Id: 0 (optional parameter) 7
Routing Examples (3)
http://localhost/Products
Controller: Products
Action: Index
Id: 0 (optional parameter) 8
Routing Examples (4)
http://localhost/
Controller: Home
Action: Index
Id: 0 (optional parameter) 9
Custom Route
http://localhost/Users/VGeorgiev
Controller: Users
Action: ByUsername
Username: VGeorgiev 10
Custom Route (2)
http://localhost/Users
Controller: Users
Action: ByUsername
Username: DefaultValue 11
Custom Route (3)
?
http://localhost/Users
12
Route Constraints
Constraints are rules on the URL segments
All the constraints are regular expression compatible with class
Regex
Defined as one of the routes.MapRoute(…) parameters
13
Custom Route Constraint
public class LocalhostConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection)
{
return httpContext.Request.IsLocal;
}
}
routes.MapRoute("Admin",
"Admin/{action}",
new { controller="Admin" },
new { isLocal = new LocalhostConstraint() }
);
14
Debugging Routes
In actions we have access to a data structure called RouteData
RouteData.Values["controller"]
RouteData.Values["action"]
RouteData.Values["id"]
We can use NuGet package: RouteDebugger
Install-Package RouteDebugger
Web.config:
<add key="RouteDebugger:Enabled" value="true" />
We can also use Glimpse for debugging routes 15
Demo: Routes
ASP.NET MVC Routing
Controllers and Actions
The brain of the applicati on
Controllers
The core component of the MVC pattern
All the controllers should be available in a folder by name
Controllers
Controller naming standard should be "NameController"
Routers instantiate controllers in every request
All requests are mapped to a specific action
Every controller should inherit Controller class
Access to Request (context) and HttpContext
18
Actions
Actions are the ultimate request destination
Public controller methods
Non-static
19
ASP.NET MVC Request
20
Action Results
Controller action response to a browser request
Inherits from the base ActionResult class
Different results types:
21
Action Results (2)
22
Action Parameters
ASP.NET MVC maps the data from the HTTP request to action
parameters in few ways:
Routing engine can pass parameters to actions
http://localhost/Users/VGeorgiev
Routing pattern: Users/{username}
URL query string can contains parameters
/Users/ByUsername?username=VGeorgiev
HTTP post data can also contain parameters
23
Action Selectors
ActionName(string name)
AcceptVerbs
HttpPost
HttpGet
HttpDelete
HttpOptions
…
NonAction
RequireHttps
ChildActionOnly – Only for Html.Action() 24
Action Filters
Apply pre- and post-processing logic
Similar to HTTP Modules
Can be applied to actions and to controllers
Global filters can be registered in GlobalFilters.
Filters (or in /App_Start/FilterConfig.cs)
Name Description
OutputCache Cache the output of a controller
ValidateInput(false) Turn off request validation and allow dangerous input (html tags)
Authorize Restrict an action to authorized users or roles
ValidateAntiForgeryToken Helps prevent cross site request forgeries
HandleError Can specify a view to render in the event of an unhandled exception
25
Custom Action Filter
Create C# class file in /Filters/
Inherit ActionFilterAttribute
We can override:
OnActionExecuting (ActionExecutingContext)
OnActionExecuted (ActionExecutedContext)
OnResultExecuting (ResultExecutingContext)
OnResultExecuted (ResultExecutedContext)
[Log]
public class DepartmentController : Controller
{ … }
27
Razor Views
Views
HTML templates of the application
A lot of view engines available
View engines execute code and provide HTML
Template + Data
= Generated
Output
UsersController.cs
UserModel.cs
33
Razor Syntax
@ – For values (HTML encoded)
<p>
Current time is: @DateTime.Now!!!
Not HTML encoded value: @Html.Raw(someVar)
</p>
/* A Multi
line C# comment
*/
}
@RenderBody() –
indicate where we want the views based
on this layout to “fill in” their core
content at that location in the HTML
38
Views and Layouts
Views don't need to specify layout since their default layout is
set in their _ViewStart file:
~/Views/_ViewStart.cshtml (code for all views)
Each view can specify custom layout pages
@{
Layout = "~/Views/Shared/_UncommonLayout.cshtml";
}
Html property has methods that return string and can be used to
generate HTML
Create inputs
Create links
Create forms
42
HTML Helpers (2)
Method Type Description
ActionLink, RouteLink Link Returns the HTML string for an HTML link
DropDownList, List Returns the HTML string for a drop-down list
DropDownListFor
ListBox, ListBoxFor List Returns the HTML string for a list box
TextArea, TextAreaFor TextArea Returns the HTML string for a text area
Partial Partial Returns the HTML string incorporated in the specified user control
RenderPartial Partial Writes the HTML string incorporated in the specified user control to the
output stream
ValidationMessage, Validation Returns the HTML string for a validation message
ValidationMessageFor
ValidationSummary Validation Returns the HTML string for a validation summary message
43
Custom Helpers
Write extension methods for the HtmlHelper
Return string or override ToString method
44
Custom Helpers (2)
Another way to write helpers:
Create folder /App_Code/
48
Demo: Areas
ASP.NET MVC structures (areas)
Summary
Routes maps URLs to controllers and actions
Controllers are the brain of our application
Actions are the ultimate request destination
Razor is a powerful engine for combining models and templates
into HTML code
Layout, sections, partials views and helpers help us to divide our
views into pieces
Our project can be divided into smaller parts containing
controllers (areas) 50
ASP.NET MVC
? ?
sti on s ? ?
Qu e ?
?
?
https://softuni.bg/courses/asp-net-mvc/
License
This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International" license
52
Free Trainings @ Software University
Software University Foundation – softuni.org
Software University – High-Quality Education,
Profession and Job for Software Developers
softuni.bg
Software University @ Facebook
facebook.com/SoftwareUniversity
Software University @ YouTube
youtube.com/SoftwareUniversity
Software University Forums – forum.softuni.bg