SlideShare a Scribd company logo
ASP.NET Core MVC
binary-studio.com
Contents
1. Model
2. View
3. Controller
Model
Model Binding
1. Form values: These are form values that go in the HTTP request
using the POST method. (including jQuery POST requests).
1. Route values: The set of route values provided by routing.
1. Query strings: The query string part of the URI. Model.IsValid
Additional types
IFormFile, IEnumerable<IFormFile>: One or more uploaded files that are part of the HTTP request.
CancelationToken: Used to cancel activity in asynchronous controllers.
Model Binding Attributes
[BindRequired]: This attribute adds a model state error if binding cannot occur.
[BindNever]: Tells the model binder to never bind to this parameter.
[FromHeader], [FromQuery], [FromRoute], [FromForm]: Use these to specify the exact binding
source you want to apply.
[FromServices]: This attribute uses dependency injection to bind parameters from services.
[FromBody]: Use the configured formatters to bind data from the request body. The formatter is
selected based on content type of the request.
[ModelBinder]: Used to override the default model binder, binding source and name.
Input/Output Formatters
Three input formatters:
– JsonInputFormatter – based on JSON.NET
– XmlSerializerInputFormatter – based on XmlSerializer (in the box, but not registered by default)
– XmlDataContractSerializerInputFormatter – based on DataContractSerializer
services.AddMvc()
.AddXmlSerializerFormatters();
services.AddMvc().Configure<MvcOptions>(options =>
{
options.InputFormatters.RemoveAll(formatter =>
formatter.Instance.GetType() == typeof(XmlDataContractSerializerInputFormatter));
});
Input/Output Formatters
Six output formatters:
– JsonOutputFormatter – based on JSON.NET
– XmlSerializerOutputFormatter – based on XmlSerializer (in the box, but not registered by default)
– XmlDataContractSerializerOutputFormatter – based on DataContractSerializer
– TextPlainFormatter – used to force a string into a text/plain content type
– HttpNoContentOutputFormatter – used to force 204 status code for null action return
– HttpNotAcceptableOutputFormatter – used to force 406 status code if no appropriate formatter can
be selected to handle the request (in the box, but not registered by default)
Model Validation
[CreditCard]: Validates the property has a credit card format.
[Compare]: Validates two properties in a model match.
[EmailAddress]: Validates the property has an email format.
[Phone]: Validates the property has a telephone format.
[Range]: Validates the property value falls within the given range.
[RegularExpression]: Validates that the data matches the specified regular expression.
[Required]: Makes a property required.
[StringLength]: Validates that a string property has at most the given maximum length.
[Url]: Validates the property has a URL format.
Model Validation
services.AddMvc(options => options.MaxModelValidationErrors = 50);
TryValidateModel(model);
Client Model Validation
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
<div class="col-md-10">
<input asp-for="ReleaseDate" class="form-control" />
<span asp-validation-for="ReleaseDate" class="text-danger"></span>
</div>
<input class="form-control" type="datetime"
data-val="true" data-val-required="The ReleaseDate field is required."
id="ReleaseDate" name="ReleaseDate" value="" />
<span class="text-danger field-validation-valid"
data-valmsg-for="ReleaseDate" data-valmsg-replace="true"></span>
Remote Client Validation
public class User
{
[Remote(action: "VerifyEmail", controller: "Users")]
public string Email { get; set; }
} [AcceptVerbs("Get", "Post")]
public IActionResult VerifyEmail(string email)
{
if (!_userRepository.VerifyEmail(email))
{
return Json(data: $"Email {email} is already in use.");
}
return Json(data: true);
}
Response Data
IActionResult
return View(_myModel);
Json()
return Json(_authorRepository.List());
Content()
return Content("Some content.");
POCOs
[HttpGet("{alias}")]
public Author Get(string alias)
{
return _authorRepository.GetByAlias(alias);
}
Other (Ok(), NotFound(), …)
View
Tag Helpers
@Html.Label("FirstName", "First Name:", new {@class="caption"})
<label class="caption" asp-for="FirstName">First Name</label>
<label class="caption" for="FirstName">Name First</label>
Using Tag Helpers
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers // Add all tag helpers
@removeTabHelper *, Microsoft.AspNetCore.Mvc.TagHelpers // Remove all tag helpers
@tagHelperPrefix th:
<!span asp-validation-for="Email" class="text-danger"></!span> // Disable tag helper
<th:label asp-validation-for="Email" class="text-danger"></th:label> // Use prefix
Tag Helpers In Forms
<form asp-controller="Demo" asp-action="Register" method="post">
<!-- Input and Submit elements -->
</form>
<form method="post" action="/Demo/Register">
<!-- Input and Submit elements -->
<input name="__RequestVerificationToken" type="hidden" value="<removed for
brevity>" />
</form>
Custom Tag Helper
public class EmailTagHelper : TagHelper
{
private const string EmailDomain = "contoso.com";
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "a"; // Replaces <email> with <a> tag
var content = await output.GetChildContentAsync();
var target = content.GetContent() + "@" + EmailDomain;
output.Attributes.SetAttribute("href", "mailto:" + target);
output.Content.SetContent(target);
}
}
<email>Support</email> <a href="mailto:Support@contoso.com">Support@contoso.com</a>
Dependency Injection
services.AddTransient<StatisticsService>();
@inject StatisticsService StatsService
<h1>Total Items: @await StatsService.GetCount()</h1>
View Component
<div>
@await Component.InvokeAsync("NameOfComponent", <anonymous type containing parameters>)
</div>
public IActionResult IndexVC()
{
return ViewComponent("MyList", new { count = 2 });
}
View Component
public class MyListViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(int count)
{
var items = await GetItemsAsync();
return View(items.Take(count));
}
private Task<List<string>> GetItemsAsync()
{
return Task.FromResult(new List<string>{“string1”, “string2”, “string3”});
}
}
Views/Shared/Components/MyList
@model IEnumerable<string>
<h3>Priority Items</h3>
<ul>
@foreach (var item in Model)
{
<li>@item</li>
}
</ul>
Controller
Routing
Areas
Filters
Error handling
Dependency Injection

More Related Content

What's hot

Complex Data Binding
Complex Data BindingComplex Data Binding
Complex Data Binding
Doncho Minkov
 
Angular Presentation
Angular PresentationAngular Presentation
Angular Presentation
Adam Moore
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 

What's hot (19)

J2EE jsp_03
J2EE jsp_03J2EE jsp_03
J2EE jsp_03
 
Deployment
DeploymentDeployment
Deployment
 
Web 2 | CSS - Cascading Style Sheets
Web 2 | CSS - Cascading Style SheetsWeb 2 | CSS - Cascading Style Sheets
Web 2 | CSS - Cascading Style Sheets
 
Complex Data Binding
Complex Data BindingComplex Data Binding
Complex Data Binding
 
JavaScript
JavaScriptJavaScript
JavaScript
 
JPA Best Practices
JPA Best PracticesJPA Best Practices
JPA Best Practices
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
 
Angular Presentation
Angular PresentationAngular Presentation
Angular Presentation
 
Struts2
Struts2Struts2
Struts2
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)
 
Spring MVC Annotations
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC Annotations
 
Scope demystified - AngularJS
Scope demystified - AngularJSScope demystified - AngularJS
Scope demystified - AngularJS
 
Web 6 | JavaScript DOM
Web 6 | JavaScript DOMWeb 6 | JavaScript DOM
Web 6 | JavaScript DOM
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
Lab#1 - Front End Development
Lab#1 - Front End DevelopmentLab#1 - Front End Development
Lab#1 - Front End Development
 
Books
BooksBooks
Books
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
6.2\9 SSIS 2008R2_Training - DataFlow Transformations
6.2\9 SSIS 2008R2_Training - DataFlow Transformations6.2\9 SSIS 2008R2_Training - DataFlow Transformations
6.2\9 SSIS 2008R2_Training - DataFlow Transformations
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 

Viewers also liked

Morgenbooster / Responsive Design 2.0 / 8. + 22. maj 2013
Morgenbooster / Responsive Design 2.0 / 8. + 22. maj 2013Morgenbooster / Responsive Design 2.0 / 8. + 22. maj 2013
Morgenbooster / Responsive Design 2.0 / 8. + 22. maj 2013
1508 A/S
 
Adam Wagner, "Biznes dla registrarów i niezbędne narzędzi dla kadry zarządzaj...
Adam Wagner, "Biznes dla registrarów i niezbędne narzędzi dla kadry zarządzaj...Adam Wagner, "Biznes dla registrarów i niezbędne narzędzi dla kadry zarządzaj...
Adam Wagner, "Biznes dla registrarów i niezbędne narzędzi dla kadry zarządzaj...
Webhosting.pl
 
Conceptualización grupo 3
Conceptualización grupo 3Conceptualización grupo 3
Conceptualización grupo 3
Ana Linares
 
Servicios educ. 2014 ceprec
Servicios educ. 2014 ceprecServicios educ. 2014 ceprec
Servicios educ. 2014 ceprec
Fito Mayen
 

Viewers also liked (20)

Vilnius
VilniusVilnius
Vilnius
 
Understanding Land Investment Deals in Africa
Understanding Land Investment Deals in AfricaUnderstanding Land Investment Deals in Africa
Understanding Land Investment Deals in Africa
 
Morgenbooster / Responsive Design 2.0 / 8. + 22. maj 2013
Morgenbooster / Responsive Design 2.0 / 8. + 22. maj 2013Morgenbooster / Responsive Design 2.0 / 8. + 22. maj 2013
Morgenbooster / Responsive Design 2.0 / 8. + 22. maj 2013
 
Learning the Open Source Way Newbie Guide
Learning the Open Source Way Newbie GuideLearning the Open Source Way Newbie Guide
Learning the Open Source Way Newbie Guide
 
Adam Wagner, "Biznes dla registrarów i niezbędne narzędzi dla kadry zarządzaj...
Adam Wagner, "Biznes dla registrarów i niezbędne narzędzi dla kadry zarządzaj...Adam Wagner, "Biznes dla registrarów i niezbędne narzędzi dla kadry zarządzaj...
Adam Wagner, "Biznes dla registrarów i niezbędne narzędzi dla kadry zarządzaj...
 
Brochure OrgPublisher - ORGANIGRAMAS - HOLL URSULA
Brochure OrgPublisher - ORGANIGRAMAS - HOLL URSULABrochure OrgPublisher - ORGANIGRAMAS - HOLL URSULA
Brochure OrgPublisher - ORGANIGRAMAS - HOLL URSULA
 
Akta oog (zuzenketa)
Akta oog (zuzenketa)Akta oog (zuzenketa)
Akta oog (zuzenketa)
 
Presentation sbs ab
Presentation sbs abPresentation sbs ab
Presentation sbs ab
 
N4 T.5edtion Uk
N4 T.5edtion UkN4 T.5edtion Uk
N4 T.5edtion Uk
 
Web 2.0 armet - ibañez - romero
Web 2.0   armet - ibañez - romeroWeb 2.0   armet - ibañez - romero
Web 2.0 armet - ibañez - romero
 
Conceptualización grupo 3
Conceptualización grupo 3Conceptualización grupo 3
Conceptualización grupo 3
 
Airborne Recorders - Curtiss-Wright Controls Avionics & Electronics
Airborne Recorders - Curtiss-Wright Controls Avionics & ElectronicsAirborne Recorders - Curtiss-Wright Controls Avionics & Electronics
Airborne Recorders - Curtiss-Wright Controls Avionics & Electronics
 
Content Strategy applied: An eBay use case
Content Strategy applied: An eBay use caseContent Strategy applied: An eBay use case
Content Strategy applied: An eBay use case
 
DunaPro Group Introduction 2011 - English
DunaPro Group Introduction 2011 - EnglishDunaPro Group Introduction 2011 - English
DunaPro Group Introduction 2011 - English
 
Servicios educ. 2014 ceprec
Servicios educ. 2014 ceprecServicios educ. 2014 ceprec
Servicios educ. 2014 ceprec
 
Nietzsche Humano Demasiado Humano
Nietzsche   Humano Demasiado HumanoNietzsche   Humano Demasiado Humano
Nietzsche Humano Demasiado Humano
 
1st day presentation Semi14
1st day presentation Semi141st day presentation Semi14
1st day presentation Semi14
 
Crisis y mercado del lujo: nuevos Mitos, nuevos ritos
Crisis y mercado del lujo: nuevos Mitos, nuevos ritosCrisis y mercado del lujo: nuevos Mitos, nuevos ritos
Crisis y mercado del lujo: nuevos Mitos, nuevos ritos
 
Potasa quelatada neutra agrares espanol
Potasa quelatada neutra agrares espanolPotasa quelatada neutra agrares espanol
Potasa quelatada neutra agrares espanol
 
What is transfer of learning?
What is transfer of learning?What is transfer of learning?
What is transfer of learning?
 

Similar to Academy PRO: ASP .NET Core MVC

Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
SharePoint Saturday NY
 
jQuery : Talk to server with Ajax
jQuery : Talk to server with AjaxjQuery : Talk to server with Ajax
jQuery : Talk to server with Ajax
Wildan Maulana
 
Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010
Rob Windsor
 
Introduction to Everit Component Registry - B Zsoldos
Introduction to Everit Component Registry - B ZsoldosIntroduction to Everit Component Registry - B Zsoldos
Introduction to Everit Component Registry - B Zsoldos
mfrancis
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
Aren Zomorodian
 

Similar to Academy PRO: ASP .NET Core MVC (20)

Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
 
AJAX
AJAXAJAX
AJAX
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
 
jQuery : Talk to server with Ajax
jQuery : Talk to server with AjaxjQuery : Talk to server with Ajax
jQuery : Talk to server with Ajax
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010
 
ERRest and Dojo
ERRest and DojoERRest and Dojo
ERRest and Dojo
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
 
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIThe Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
 
Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIIntroduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST API
 
Validate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation apiValidate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation api
 
Dev308
Dev308Dev308
Dev308
 
Introduction to Everit Component Registry - B Zsoldos
Introduction to Everit Component Registry - B ZsoldosIntroduction to Everit Component Registry - B Zsoldos
Introduction to Everit Component Registry - B Zsoldos
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Struts 2
Struts 2Struts 2
Struts 2
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2
 
Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0
 
Servlets intro
Servlets introServlets intro
Servlets intro
 

More from Binary Studio

More from Binary Studio (20)

Academy PRO: D3, part 3
Academy PRO: D3, part 3Academy PRO: D3, part 3
Academy PRO: D3, part 3
 
Academy PRO: D3, part 1
Academy PRO: D3, part 1Academy PRO: D3, part 1
Academy PRO: D3, part 1
 
Academy PRO: Cryptography 3
Academy PRO: Cryptography 3Academy PRO: Cryptography 3
Academy PRO: Cryptography 3
 
Academy PRO: Cryptography 1
Academy PRO: Cryptography 1Academy PRO: Cryptography 1
Academy PRO: Cryptography 1
 
Academy PRO: Advanced React Ecosystem. MobX
Academy PRO: Advanced React Ecosystem. MobXAcademy PRO: Advanced React Ecosystem. MobX
Academy PRO: Advanced React Ecosystem. MobX
 
Academy PRO: Docker. Part 4
Academy PRO: Docker. Part 4Academy PRO: Docker. Part 4
Academy PRO: Docker. Part 4
 
Academy PRO: Docker. Part 2
Academy PRO: Docker. Part 2Academy PRO: Docker. Part 2
Academy PRO: Docker. Part 2
 
Academy PRO: Docker. Part 1
Academy PRO: Docker. Part 1Academy PRO: Docker. Part 1
Academy PRO: Docker. Part 1
 
Binary Studio Academy 2017: JS team project - Orderly
Binary Studio Academy 2017: JS team project - OrderlyBinary Studio Academy 2017: JS team project - Orderly
Binary Studio Academy 2017: JS team project - Orderly
 
Binary Studio Academy 2017: .NET team project - Unicorn
Binary Studio Academy 2017: .NET team project - UnicornBinary Studio Academy 2017: .NET team project - Unicorn
Binary Studio Academy 2017: .NET team project - Unicorn
 
Academy PRO: React native - miscellaneous
Academy PRO: React native - miscellaneousAcademy PRO: React native - miscellaneous
Academy PRO: React native - miscellaneous
 
Academy PRO: React native - publish
Academy PRO: React native - publishAcademy PRO: React native - publish
Academy PRO: React native - publish
 
Academy PRO: React native - navigation
Academy PRO: React native - navigationAcademy PRO: React native - navigation
Academy PRO: React native - navigation
 
Academy PRO: React native - building first scenes
Academy PRO: React native - building first scenesAcademy PRO: React native - building first scenes
Academy PRO: React native - building first scenes
 
Academy PRO: React Native - introduction
Academy PRO: React Native - introductionAcademy PRO: React Native - introduction
Academy PRO: React Native - introduction
 
Academy PRO: Push notifications. Denis Beketsky
Academy PRO: Push notifications. Denis BeketskyAcademy PRO: Push notifications. Denis Beketsky
Academy PRO: Push notifications. Denis Beketsky
 
Academy PRO: Docker. Lecture 4
Academy PRO: Docker. Lecture 4Academy PRO: Docker. Lecture 4
Academy PRO: Docker. Lecture 4
 
Academy PRO: Docker. Lecture 3
Academy PRO: Docker. Lecture 3Academy PRO: Docker. Lecture 3
Academy PRO: Docker. Lecture 3
 
Academy PRO: Docker. Lecture 2
Academy PRO: Docker. Lecture 2Academy PRO: Docker. Lecture 2
Academy PRO: Docker. Lecture 2
 
Academy PRO: Docker. Lecture 1
Academy PRO: Docker. Lecture 1Academy PRO: Docker. Lecture 1
Academy PRO: Docker. Lecture 1
 

Recently uploaded

AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
Alluxio, Inc.
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
mbmh111980
 

Recently uploaded (20)

Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 
INGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignINGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by Design
 
A Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationA Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data Migration
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabber
 
Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting software
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 

Academy PRO: ASP .NET Core MVC

  • 4. Model Binding 1. Form values: These are form values that go in the HTTP request using the POST method. (including jQuery POST requests). 1. Route values: The set of route values provided by routing. 1. Query strings: The query string part of the URI. Model.IsValid
  • 5. Additional types IFormFile, IEnumerable<IFormFile>: One or more uploaded files that are part of the HTTP request. CancelationToken: Used to cancel activity in asynchronous controllers.
  • 6. Model Binding Attributes [BindRequired]: This attribute adds a model state error if binding cannot occur. [BindNever]: Tells the model binder to never bind to this parameter. [FromHeader], [FromQuery], [FromRoute], [FromForm]: Use these to specify the exact binding source you want to apply. [FromServices]: This attribute uses dependency injection to bind parameters from services. [FromBody]: Use the configured formatters to bind data from the request body. The formatter is selected based on content type of the request. [ModelBinder]: Used to override the default model binder, binding source and name.
  • 7. Input/Output Formatters Three input formatters: – JsonInputFormatter – based on JSON.NET – XmlSerializerInputFormatter – based on XmlSerializer (in the box, but not registered by default) – XmlDataContractSerializerInputFormatter – based on DataContractSerializer services.AddMvc() .AddXmlSerializerFormatters(); services.AddMvc().Configure<MvcOptions>(options => { options.InputFormatters.RemoveAll(formatter => formatter.Instance.GetType() == typeof(XmlDataContractSerializerInputFormatter)); });
  • 8. Input/Output Formatters Six output formatters: – JsonOutputFormatter – based on JSON.NET – XmlSerializerOutputFormatter – based on XmlSerializer (in the box, but not registered by default) – XmlDataContractSerializerOutputFormatter – based on DataContractSerializer – TextPlainFormatter – used to force a string into a text/plain content type – HttpNoContentOutputFormatter – used to force 204 status code for null action return – HttpNotAcceptableOutputFormatter – used to force 406 status code if no appropriate formatter can be selected to handle the request (in the box, but not registered by default)
  • 9. Model Validation [CreditCard]: Validates the property has a credit card format. [Compare]: Validates two properties in a model match. [EmailAddress]: Validates the property has an email format. [Phone]: Validates the property has a telephone format. [Range]: Validates the property value falls within the given range. [RegularExpression]: Validates that the data matches the specified regular expression. [Required]: Makes a property required. [StringLength]: Validates that a string property has at most the given maximum length. [Url]: Validates the property has a URL format.
  • 10. Model Validation services.AddMvc(options => options.MaxModelValidationErrors = 50); TryValidateModel(model);
  • 11. Client Model Validation <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script> <div class="col-md-10"> <input asp-for="ReleaseDate" class="form-control" /> <span asp-validation-for="ReleaseDate" class="text-danger"></span> </div> <input class="form-control" type="datetime" data-val="true" data-val-required="The ReleaseDate field is required." id="ReleaseDate" name="ReleaseDate" value="" /> <span class="text-danger field-validation-valid" data-valmsg-for="ReleaseDate" data-valmsg-replace="true"></span>
  • 12. Remote Client Validation public class User { [Remote(action: "VerifyEmail", controller: "Users")] public string Email { get; set; } } [AcceptVerbs("Get", "Post")] public IActionResult VerifyEmail(string email) { if (!_userRepository.VerifyEmail(email)) { return Json(data: $"Email {email} is already in use."); } return Json(data: true); }
  • 13. Response Data IActionResult return View(_myModel); Json() return Json(_authorRepository.List()); Content() return Content("Some content."); POCOs [HttpGet("{alias}")] public Author Get(string alias) { return _authorRepository.GetByAlias(alias); } Other (Ok(), NotFound(), …)
  • 14. View
  • 15. Tag Helpers @Html.Label("FirstName", "First Name:", new {@class="caption"}) <label class="caption" asp-for="FirstName">First Name</label> <label class="caption" for="FirstName">Name First</label>
  • 16. Using Tag Helpers @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers // Add all tag helpers @removeTabHelper *, Microsoft.AspNetCore.Mvc.TagHelpers // Remove all tag helpers @tagHelperPrefix th: <!span asp-validation-for="Email" class="text-danger"></!span> // Disable tag helper <th:label asp-validation-for="Email" class="text-danger"></th:label> // Use prefix
  • 17. Tag Helpers In Forms <form asp-controller="Demo" asp-action="Register" method="post"> <!-- Input and Submit elements --> </form> <form method="post" action="/Demo/Register"> <!-- Input and Submit elements --> <input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" /> </form>
  • 18. Custom Tag Helper public class EmailTagHelper : TagHelper { private const string EmailDomain = "contoso.com"; public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { output.TagName = "a"; // Replaces <email> with <a> tag var content = await output.GetChildContentAsync(); var target = content.GetContent() + "@" + EmailDomain; output.Attributes.SetAttribute("href", "mailto:" + target); output.Content.SetContent(target); } } <email>Support</email> <a href="mailto:Support@contoso.com">Support@contoso.com</a>
  • 19. Dependency Injection services.AddTransient<StatisticsService>(); @inject StatisticsService StatsService <h1>Total Items: @await StatsService.GetCount()</h1>
  • 20. View Component <div> @await Component.InvokeAsync("NameOfComponent", <anonymous type containing parameters>) </div> public IActionResult IndexVC() { return ViewComponent("MyList", new { count = 2 }); }
  • 21. View Component public class MyListViewComponent : ViewComponent { public async Task<IViewComponentResult> InvokeAsync(int count) { var items = await GetItemsAsync(); return View(items.Take(count)); } private Task<List<string>> GetItemsAsync() { return Task.FromResult(new List<string>{“string1”, “string2”, “string3”}); } } Views/Shared/Components/MyList @model IEnumerable<string> <h3>Priority Items</h3> <ul> @foreach (var item in Model) { <li>@item</li> } </ul>