SlideShare a Scribd company logo
1 of 45
Download to read offline
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framework core
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framework core
•
•
• C#
•
• ASP.NET MVC XAML
Windows 8 + 10
•
• MS SQL Server
•
• Trainer Developer
• www.reflectionit.nl
3
•
•
•
•
•
•
•
•
4
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framework core
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framework core
•
•
•
•
•
•
•
•
• https://github.com/aspnet
• http://get.asp.net
• https://docs.asp.net
7
•
8
9
•
•
•
10
•
•
•
•
• https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/powershell 12
•
•
•
•
•
•
14
15
public partial class NorthwindContext : DbContext {
#if DEBUG
// This constructor is only used for scaffolding controllers
public NorthwindContext() : base(
new DbContextOptionsBuilder<NorthwindContext>()
.UseSqlServer("Server=.sqlexpress;Database=Northwind;Trusted_Connection=True;MultipleActiveResultSets=true")
.Option​s) {
}
#endif
public NorthwindContext(DbContextOptions<NorthwindContext> options) : base(options) {
}
16
•
17
18
19
20
Async actions!
<ul class="nav navbar-nav">
<li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
<li><a asp-area="" asp-controller="Products" asp-action="Index">Products</a></li>
</ul>
21
22
@model IEnumerable<ModelsDemo.Models.Northwind.Products>
@{
ViewData["Title"] = "Products";
}
<h1>Products</h1>
<p><a asp-action="Create"><span class="glyphicon glyphicon-plus" aria-
hidden="true"></span> Create New</a></p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.ProductName)
</th>
<th>
@Html.DisplayNameFor(model => model.Supplier.CompanyName)
</th>
<th>
@Html.DisplayNameFor(model => model.Category.CategoryName)
</th>
http://getbootstrap.com/components/#glyphicons
23
<td>
<a asp-action="Edit" asp-route-id="@item.ProductId">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
</a> |
<a asp-action="Details" asp-route-id="@item.ProductId">
<span class="glyphicon glyphicon-open" aria-hidden="true"></span>
</a> |
<a asp-action="Delete" asp-route-id="@item.ProductId">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</a>
</td>
•
@model IEnumerable<ModelsDemo.Models.Northwind.Products>
@{
ViewData["Title"] = "Products";
}
<h1>Products</h1>
<form method="post" class="form-inline">
<input name="filter" class="form-control" value="@ViewData["Filter"]" />
<button type="submit" class="btn btn-info btn-sm">Search</button>
</form>
<br />
<p>
<a asp-action="Create">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Create New
</a>
</p>
<table class="table">
24
public class ProductsController : Controller
{
private readonly NorthwindContext _context;
public ProductsController(NorthwindContext context)
{
_context = context;
}
// GET: Products
public async Task<IActionResult> Index()
{
var qry = _context.Products.AsNoTracking().Include(p => p.Category).Include(p => p.Supplier);
return View(await qry.ToListAsync());
}
[HttpPost]
public async Task<IActionResult> Index(string filter) {
ViewData["Filter"] = filter;
var qry = _context.Products.AsNoTracking().Include(p => p.Category).Include(p => p.Supplier)
.Where(p => p.ProductName.Contains(filter));
return View(await qry.ToListAsync());
} 25
Add
AsNoTracking()
•
<form method="get" class="form-inline">
<input name="filter" class="form-control" value="@ViewData["Filter"]" />
<button type="submit" class="btn btn-info btn-sm">Search</button>
</form>
•
// GET: Products
public async Task<IActionResult> Index(string filter) {
var qry = _context.Products.AsNoTracking()
.Include(p => p.Category)
.Include(p => p.Supplier)
.OrderBy(p => p.ProductName).AsQueryable();
if (!string.IsNullOrEmpty(filter)) {
ViewData["Filter"] = filter;
qry = qry.Where(p => p.ProductName.StartsWith(filter));
}
return View(await qry.ToListAsync());
}
26
•
•
• https://github.com/sonnemaf/ReflectionIT.Mvc.Paging
•
•
•
•
•
public class SuppliersController : Controller {
...
// GET: Suppliers
public async Task<IActionResult> Index(int page = 1) {
var qry = _context.Suppliers.OrderBy(p => p.CompanyName);
var model = await PagingList<Suppliers>.CreateAsync(qry, 10, page);
return View(model);
}
28
•
•
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
...
services.AddMvc();
services.AddPaging();
•
•
@await Component.InvokeAsync("ReflectionIT.Mvc.Paging.Pager", new { pagingList = this.Model })
•
•
@await Html.PartialAsync("Pager", this.Model)
30
@model ReflectionIT.Mvc.Paging.IPagingList
@if (this.Model.PageCount > 1) {
<ul class="pagination">
@for (int i = 1; i <= Model.PageCount; i++) {
<li class="@((Model.PageIndex == i) ? "active" : null)">
@Html.ActionLink(i.ToString(),
Model.Action,
Model.GetRouteValueForPage(i))
</li>
}
</ul>
}
31
•
// GET: Products
public async Task<IActionResult> Index(string filter, int page = 1, string sortExpression = "ProductName") {
var qry = _context.Products
.Include(p => p.Category)
.Include(p => p.Supplier)
.AsQueryable();
if (!string.IsNullOrWhiteSpace(filter)) {
qry = qry.Where(p => p.ProductName.Contains(filter));
}
var model = await PagingList<Products>.CreateAsync(qry, 10, page, sortExpression, "ProductName");
model.RouteValue = new RouteValueDictionary {
{ "filter", filter}
};
return View(model);
}
32
@model ReflectionIT.Mvc.Paging.PagingList<WebApplication2.Models.Products>
@using ReflectionIT.Mvc.Paging; @*Brings SortableHeaderFor extension method into scope*@
@{
ViewData["Title"] = "Products";
}
<h1>Products</h1>
<p><a asp-action="Create">Create New</a></p>
<form method="get" asp-antiforgery="false">
<div class="form-group">
<label class="sr-only" for="filter">Filter</label>
@Html.TextBox("filter", null, null, new { type = "search", @class = "form-control", placeholder = "your filter" })
</div>
<div class="form-group">
<button class="btn btn-primary">Search</button>
</div>
</form>
@Html.Partial("Pager", this.Model)
<table class="table table-striped">
<tr>
<th>@Html.SortableHeaderFor(model => model.ProductName, "ProductName")</th>
<th>@Html.SortableHeaderFor(model => model.Category.CategoryName, "Category.CategoryName, ProductName")</th>
<th>@Html.SortableHeaderFor(model => model.Supplier.CompanyName, "Supplier.CompanyName, ProductName") </th>
<th>@Html.SortableHeaderFor(model => model.QuantityPerUnit, "QuantityPerUnit") </th>
33
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framework core
• System.ComponentModel.DataAnnotations
• Compare
•
• CustomValidation
•
• EmailAddress
•
• Range
•
• RegularExpression
•
• Required
•
• StringLength MaxLength MinLength
•
• Url
•
•
• Remote
•
•
35
public partial class Products {
public Products() {
OrderDetails = new HashSet<OrderDetails>();
}
[Key]
public int ProductID { get; set; }
public int? CategoryID { get; set; }
public bool Discontinued { get; set; }
[Required]
[MaxLength(40)]
[MinLength(4)]
public string ProductName { get; set; }
[Range(1, 1000)]
public decimal? UnitPrice { get; set; }
[MaxLength(20)]
public string QuantityPerUnit { get; set; }
...
36
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framework core
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framework core
public class SuppliersController : Controller {
public JsonResult IsCompanyNameAvailable(int? supplierId, string companyName) {
if (!_context.Suppliers.Any(sup => (!supplierId.HasValue || sup.SupplierId != supplierId) &&
sup.CompanyName == companyName)) {
return Json(true);
}
return Json($"{companyName} is already used");
}
public partial class Suppliers {
[Column("SupplierID")]
[Key]
public int SupplierId { get; set; }
[Required]
[MaxLength(40)]
[Microsoft.AspNetCore.Mvc.Remote("IsCompanyNameAvailable", "Suppliers", "", AdditionalFields = "SupplierId")]
public string CompanyName { get; set; }
// POST: Products/Create
[HttpPost][ValidateAntiForgeryToken]
public async Task<IActionResult>
Create([Bind("ProductId,CategoryId,Discontinued,ProductName,QuantityPerUnit,ReorderLevel,SupplierId,UnitPrice,UnitsInStock,UnitsOnOr
der")] Products products) {
if (ModelState.IsValid) {
_context.Add(products);
//await _context.SaveChangesAsync();
if (await TrySaveChangesAsync()) {
return RedirectToAction("Index");
}
}
ViewData["CategoryId"] = new SelectList(_context.Categories, "CategoryId", "CategoryName", products.CategoryId);
ViewData["SupplierId"] = new SelectList(_context.Suppliers, "SupplierId", "CompanyName", products.SupplierId);
return View(products);
}
private async Task<bool> TrySaveChangesAsync() {
try {
await _context.SaveChangesAsync();
return true;
} catch (DbUpdateException ex) when ((ex.InnerException as SqlException).Number == 2601) {
this.ModelState.AddModelError(string.Empty, "ProductName must be unique");
return false;
} catch (Exception ex) {
this.ModelState.AddModelError(string.Empty, ex.Message);
return false;
}
}
• DisplayAttribute
•
• DisplayFormatAttribute
•
• HiddenInputAttribute
•
• UIHint
•
• DataTypeAttribute
•
41
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framework core
@{
string style = null;
if (ViewData.Model < 20) {
style = "color: red";
}
if (ViewData.Model > 50) {
style = "color: green";
}
}
<span style="@style">€ @(ViewData.Model?.ToString("N2"))</span>
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framework core
45
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framework core

More Related Content

What's hot

Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...SPTechCon
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6Andy Butland
 
SharePoint Conference 2018 - Build an intelligent application by connecting i...
SharePoint Conference 2018 - Build an intelligent application by connecting i...SharePoint Conference 2018 - Build an intelligent application by connecting i...
SharePoint Conference 2018 - Build an intelligent application by connecting i...Sébastien Levert
 
iOS viper presentation
iOS viper presentationiOS viper presentation
iOS viper presentationRajat Datta
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvcGuo Albert
 
Apex Code Analysis Using the Tooling API and Canvas
Apex Code Analysis Using the Tooling API and CanvasApex Code Analysis Using the Tooling API and Canvas
Apex Code Analysis Using the Tooling API and CanvasSalesforce Developers
 
Asp.net mvc 5 course module 1 overview
Asp.net mvc 5 course   module 1 overviewAsp.net mvc 5 course   module 1 overview
Asp.net mvc 5 course module 1 overviewSergey Seletsky
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application Madhuri Kavade
 
Mobile for SharePoint with Windows Phone
Mobile for SharePoint with Windows PhoneMobile for SharePoint with Windows Phone
Mobile for SharePoint with Windows PhoneEdgewater
 
SharePoint 2013 APIs
SharePoint 2013 APIsSharePoint 2013 APIs
SharePoint 2013 APIsJohn Calvert
 
Top 10 HTML5 features every developer should know!
Top 10 HTML5 features every developer should know!Top 10 HTML5 features every developer should know!
Top 10 HTML5 features every developer should know!Gill Cleeren
 
Breaking the limits_of_page_objects
Breaking the limits_of_page_objectsBreaking the limits_of_page_objects
Breaking the limits_of_page_objectsRobert Bossek
 
D2W Stateful Controllers
D2W Stateful ControllersD2W Stateful Controllers
D2W Stateful ControllersWO Community
 
BP204 - Take a REST and put your data to work with APIs!
BP204 - Take a REST and put your data to work with APIs!BP204 - Take a REST and put your data to work with APIs!
BP204 - Take a REST and put your data to work with APIs!Craig Schumann
 
Building a Twitter App with Silverlight 3 - Part 2
Building a Twitter App with Silverlight 3 - Part 2Building a Twitter App with Silverlight 3 - Part 2
Building a Twitter App with Silverlight 3 - Part 2Clint Edmonson
 
IBM Connect 2014 - AD205: Creating State-of-the-Art Web Applications with Dom...
IBM Connect 2014 - AD205: Creating State-of-the-Art Web Applications with Dom...IBM Connect 2014 - AD205: Creating State-of-the-Art Web Applications with Dom...
IBM Connect 2014 - AD205: Creating State-of-the-Art Web Applications with Dom...Dave Delay
 

What's hot (20)

Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6
 
SharePoint Conference 2018 - Build an intelligent application by connecting i...
SharePoint Conference 2018 - Build an intelligent application by connecting i...SharePoint Conference 2018 - Build an intelligent application by connecting i...
SharePoint Conference 2018 - Build an intelligent application by connecting i...
 
iOS viper presentation
iOS viper presentationiOS viper presentation
iOS viper presentation
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
 
Apex Code Analysis Using the Tooling API and Canvas
Apex Code Analysis Using the Tooling API and CanvasApex Code Analysis Using the Tooling API and Canvas
Apex Code Analysis Using the Tooling API and Canvas
 
JAX-WS Basics
JAX-WS BasicsJAX-WS Basics
JAX-WS Basics
 
Asp.net mvc 5 course module 1 overview
Asp.net mvc 5 course   module 1 overviewAsp.net mvc 5 course   module 1 overview
Asp.net mvc 5 course module 1 overview
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application
 
Mobile for SharePoint with Windows Phone
Mobile for SharePoint with Windows PhoneMobile for SharePoint with Windows Phone
Mobile for SharePoint with Windows Phone
 
SharePoint 2013 APIs
SharePoint 2013 APIsSharePoint 2013 APIs
SharePoint 2013 APIs
 
Top 10 HTML5 features every developer should know!
Top 10 HTML5 features every developer should know!Top 10 HTML5 features every developer should know!
Top 10 HTML5 features every developer should know!
 
Breaking the limits_of_page_objects
Breaking the limits_of_page_objectsBreaking the limits_of_page_objects
Breaking the limits_of_page_objects
 
D2W Stateful Controllers
D2W Stateful ControllersD2W Stateful Controllers
D2W Stateful Controllers
 
Web works hol
Web works holWeb works hol
Web works hol
 
BP204 - Take a REST and put your data to work with APIs!
BP204 - Take a REST and put your data to work with APIs!BP204 - Take a REST and put your data to work with APIs!
BP204 - Take a REST and put your data to work with APIs!
 
Building a Twitter App with Silverlight 3 - Part 2
Building a Twitter App with Silverlight 3 - Part 2Building a Twitter App with Silverlight 3 - Part 2
Building a Twitter App with Silverlight 3 - Part 2
 
Tutorial asp.net
Tutorial  asp.netTutorial  asp.net
Tutorial asp.net
 
IBM Connect 2014 - AD205: Creating State-of-the-Art Web Applications with Dom...
IBM Connect 2014 - AD205: Creating State-of-the-Art Web Applications with Dom...IBM Connect 2014 - AD205: Creating State-of-the-Art Web Applications with Dom...
IBM Connect 2014 - AD205: Creating State-of-the-Art Web Applications with Dom...
 
Web forms in ASP.net
Web forms in ASP.netWeb forms in ASP.net
Web forms in ASP.net
 

Viewers also liked

What's new in Blend for Visual Studio 2015
What's new in Blend for Visual Studio 2015What's new in Blend for Visual Studio 2015
What's new in Blend for Visual Studio 2015Fons Sonnemans
 
Developing and Deploying Windows 10 Apps
Developing and Deploying Windows 10 AppsDeveloping and Deploying Windows 10 Apps
Developing and Deploying Windows 10 AppsFons Sonnemans
 
Coding for kids - TechDaysNL 2015
Coding for kids - TechDaysNL 2015Coding for kids - TechDaysNL 2015
Coding for kids - TechDaysNL 2015Fons Sonnemans
 
Building & Designing Windows 10 Universal Windows Apps using XAML and C#
Building & Designing Windows 10 Universal Windows Apps using XAML and C#Building & Designing Windows 10 Universal Windows Apps using XAML and C#
Building & Designing Windows 10 Universal Windows Apps using XAML and C#Fons Sonnemans
 
Демоверсия бизнес план животноводческой фермы
Демоверсия бизнес план животноводческой фермыДемоверсия бизнес план животноводческой фермы
Демоверсия бизнес план животноводческой фермыolegudobno
 
Управление тестированием в Agile
Управление тестированием в AgileУправление тестированием в Agile
Управление тестированием в AgileAskhat Urazbaev
 

Viewers also liked (6)

What's new in Blend for Visual Studio 2015
What's new in Blend for Visual Studio 2015What's new in Blend for Visual Studio 2015
What's new in Blend for Visual Studio 2015
 
Developing and Deploying Windows 10 Apps
Developing and Deploying Windows 10 AppsDeveloping and Deploying Windows 10 Apps
Developing and Deploying Windows 10 Apps
 
Coding for kids - TechDaysNL 2015
Coding for kids - TechDaysNL 2015Coding for kids - TechDaysNL 2015
Coding for kids - TechDaysNL 2015
 
Building & Designing Windows 10 Universal Windows Apps using XAML and C#
Building & Designing Windows 10 Universal Windows Apps using XAML and C#Building & Designing Windows 10 Universal Windows Apps using XAML and C#
Building & Designing Windows 10 Universal Windows Apps using XAML and C#
 
Демоверсия бизнес план животноводческой фермы
Демоверсия бизнес план животноводческой фермыДемоверсия бизнес план животноводческой фермы
Демоверсия бизнес план животноводческой фермы
 
Управление тестированием в Agile
Управление тестированием в AgileУправление тестированием в Agile
Управление тестированием в Agile
 

Similar to TechDays 2016 - Developing websites using asp.net core mvc6 and entity framework core

Service Oriented Architecture in Magento 2
Service Oriented Architecture in Magento 2Service Oriented Architecture in Magento 2
Service Oriented Architecture in Magento 2Max Pronko
 
My way to clean android - Android day salamanca edition
My way to clean android - Android day salamanca editionMy way to clean android - Android day salamanca edition
My way to clean android - Android day salamanca editionChristian Panadero
 
My way to clean android (EN) - Android day salamanca edition
My way to clean android (EN) - Android day salamanca editionMy way to clean android (EN) - Android day salamanca edition
My way to clean android (EN) - Android day salamanca editionChristian Panadero
 
Александр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия SwiftАлександр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия SwiftCocoaHeads
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicBadoo Development
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJiayun Zhou
 
Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...bjhargrave
 
OSGi Community Event 2010 - Dependencies, dependencies, dependencies
OSGi Community Event 2010 - Dependencies, dependencies, dependenciesOSGi Community Event 2010 - Dependencies, dependencies, dependencies
OSGi Community Event 2010 - Dependencies, dependencies, dependenciesmfrancis
 
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.NET Conf UY
 
Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03Kevin Juma
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Loiane Groner
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDMichele Capra
 
Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»SpbDotNet Community
 
GraphTour - Utilizing Powerful Extensions for Analytics & Operations
GraphTour - Utilizing Powerful Extensions for Analytics & OperationsGraphTour - Utilizing Powerful Extensions for Analytics & Operations
GraphTour - Utilizing Powerful Extensions for Analytics & OperationsNeo4j
 
.gradle 파일 정독해보기
.gradle 파일 정독해보기.gradle 파일 정독해보기
.gradle 파일 정독해보기경주 전
 
The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212Mahmoud Samir Fayed
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Eyal Vardi
 
Android dev toolbox
Android dev toolboxAndroid dev toolbox
Android dev toolboxShem Magnezi
 

Similar to TechDays 2016 - Developing websites using asp.net core mvc6 and entity framework core (20)

Linq
LinqLinq
Linq
 
Service Oriented Architecture in Magento 2
Service Oriented Architecture in Magento 2Service Oriented Architecture in Magento 2
Service Oriented Architecture in Magento 2
 
My way to clean android - Android day salamanca edition
My way to clean android - Android day salamanca editionMy way to clean android - Android day salamanca edition
My way to clean android - Android day salamanca edition
 
My way to clean android (EN) - Android day salamanca edition
My way to clean android (EN) - Android day salamanca editionMy way to clean android (EN) - Android day salamanca edition
My way to clean android (EN) - Android day salamanca edition
 
Александр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия SwiftАлександр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия Swift
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magic
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...
 
OSGi Community Event 2010 - Dependencies, dependencies, dependencies
OSGi Community Event 2010 - Dependencies, dependencies, dependenciesOSGi Community Event 2010 - Dependencies, dependencies, dependencies
OSGi Community Event 2010 - Dependencies, dependencies, dependencies
 
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
 
Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03
 
React inter3
React inter3React inter3
React inter3
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
 
Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»
 
GraphTour - Utilizing Powerful Extensions for Analytics & Operations
GraphTour - Utilizing Powerful Extensions for Analytics & OperationsGraphTour - Utilizing Powerful Extensions for Analytics & Operations
GraphTour - Utilizing Powerful Extensions for Analytics & Operations
 
.gradle 파일 정독해보기
.gradle 파일 정독해보기.gradle 파일 정독해보기
.gradle 파일 정독해보기
 
The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)
 
Android dev toolbox
Android dev toolboxAndroid dev toolbox
Android dev toolbox
 

More from Fons Sonnemans

Writing High Peformance C# 7 Code
Writing High Peformance C# 7 CodeWriting High Peformance C# 7 Code
Writing High Peformance C# 7 CodeFons Sonnemans
 
New XAML/UWP features in Windows 10 Fall Creators Update
New XAML/UWP features in Windows 10 Fall Creators UpdateNew XAML/UWP features in Windows 10 Fall Creators Update
New XAML/UWP features in Windows 10 Fall Creators UpdateFons Sonnemans
 
Coding for kids - TechDays 2017
Coding for kids - TechDays 2017Coding for kids - TechDays 2017
Coding for kids - TechDays 2017Fons Sonnemans
 
Twelve ways to make your apps suck less
Twelve ways to make your apps suck lessTwelve ways to make your apps suck less
Twelve ways to make your apps suck lessFons Sonnemans
 
What’s new in XAML and Tooling for Windows 8.1
What’s new in XAML and Tooling for Windows 8.1What’s new in XAML and Tooling for Windows 8.1
What’s new in XAML and Tooling for Windows 8.1Fons Sonnemans
 
Designing XAML apps using Blend for Visual Studio 2013
Designing XAML apps using Blend for Visual Studio 2013Designing XAML apps using Blend for Visual Studio 2013
Designing XAML apps using Blend for Visual Studio 2013Fons Sonnemans
 
Making money with apps
Making money with appsMaking money with apps
Making money with appsFons Sonnemans
 

More from Fons Sonnemans (8)

Xamarin Froms 4.x
Xamarin Froms 4.xXamarin Froms 4.x
Xamarin Froms 4.x
 
Writing High Peformance C# 7 Code
Writing High Peformance C# 7 CodeWriting High Peformance C# 7 Code
Writing High Peformance C# 7 Code
 
New XAML/UWP features in Windows 10 Fall Creators Update
New XAML/UWP features in Windows 10 Fall Creators UpdateNew XAML/UWP features in Windows 10 Fall Creators Update
New XAML/UWP features in Windows 10 Fall Creators Update
 
Coding for kids - TechDays 2017
Coding for kids - TechDays 2017Coding for kids - TechDays 2017
Coding for kids - TechDays 2017
 
Twelve ways to make your apps suck less
Twelve ways to make your apps suck lessTwelve ways to make your apps suck less
Twelve ways to make your apps suck less
 
What’s new in XAML and Tooling for Windows 8.1
What’s new in XAML and Tooling for Windows 8.1What’s new in XAML and Tooling for Windows 8.1
What’s new in XAML and Tooling for Windows 8.1
 
Designing XAML apps using Blend for Visual Studio 2013
Designing XAML apps using Blend for Visual Studio 2013Designing XAML apps using Blend for Visual Studio 2013
Designing XAML apps using Blend for Visual Studio 2013
 
Making money with apps
Making money with appsMaking money with apps
Making money with apps
 

Recently uploaded

OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 

Recently uploaded (20)

OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 

TechDays 2016 - Developing websites using asp.net core mvc6 and entity framework core

  • 3. • • • C# • • ASP.NET MVC XAML Windows 8 + 10 • • MS SQL Server • • Trainer Developer • www.reflectionit.nl 3
  • 9. 9
  • 14. 15
  • 15. public partial class NorthwindContext : DbContext { #if DEBUG // This constructor is only used for scaffolding controllers public NorthwindContext() : base( new DbContextOptionsBuilder<NorthwindContext>() .UseSqlServer("Server=.sqlexpress;Database=Northwind;Trusted_Connection=True;MultipleActiveResultSets=true") .Option​s) { } #endif public NorthwindContext(DbContextOptions<NorthwindContext> options) : base(options) { } 16
  • 17. 18
  • 18. 19
  • 20. <ul class="nav navbar-nav"> <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li> <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li> <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li> <li><a asp-area="" asp-controller="Products" asp-action="Index">Products</a></li> </ul> 21
  • 21. 22
  • 22. @model IEnumerable<ModelsDemo.Models.Northwind.Products> @{ ViewData["Title"] = "Products"; } <h1>Products</h1> <p><a asp-action="Create"><span class="glyphicon glyphicon-plus" aria- hidden="true"></span> Create New</a></p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.ProductName) </th> <th> @Html.DisplayNameFor(model => model.Supplier.CompanyName) </th> <th> @Html.DisplayNameFor(model => model.Category.CategoryName) </th> http://getbootstrap.com/components/#glyphicons 23 <td> <a asp-action="Edit" asp-route-id="@item.ProductId"> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> </a> | <a asp-action="Details" asp-route-id="@item.ProductId"> <span class="glyphicon glyphicon-open" aria-hidden="true"></span> </a> | <a asp-action="Delete" asp-route-id="@item.ProductId"> <span class="glyphicon glyphicon-remove" aria-hidden="true"></span> </a> </td>
  • 23. • @model IEnumerable<ModelsDemo.Models.Northwind.Products> @{ ViewData["Title"] = "Products"; } <h1>Products</h1> <form method="post" class="form-inline"> <input name="filter" class="form-control" value="@ViewData["Filter"]" /> <button type="submit" class="btn btn-info btn-sm">Search</button> </form> <br /> <p> <a asp-action="Create"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Create New </a> </p> <table class="table"> 24
  • 24. public class ProductsController : Controller { private readonly NorthwindContext _context; public ProductsController(NorthwindContext context) { _context = context; } // GET: Products public async Task<IActionResult> Index() { var qry = _context.Products.AsNoTracking().Include(p => p.Category).Include(p => p.Supplier); return View(await qry.ToListAsync()); } [HttpPost] public async Task<IActionResult> Index(string filter) { ViewData["Filter"] = filter; var qry = _context.Products.AsNoTracking().Include(p => p.Category).Include(p => p.Supplier) .Where(p => p.ProductName.Contains(filter)); return View(await qry.ToListAsync()); } 25 Add AsNoTracking()
  • 25. • <form method="get" class="form-inline"> <input name="filter" class="form-control" value="@ViewData["Filter"]" /> <button type="submit" class="btn btn-info btn-sm">Search</button> </form> • // GET: Products public async Task<IActionResult> Index(string filter) { var qry = _context.Products.AsNoTracking() .Include(p => p.Category) .Include(p => p.Supplier) .OrderBy(p => p.ProductName).AsQueryable(); if (!string.IsNullOrEmpty(filter)) { ViewData["Filter"] = filter; qry = qry.Where(p => p.ProductName.StartsWith(filter)); } return View(await qry.ToListAsync()); } 26
  • 27. • public class SuppliersController : Controller { ... // GET: Suppliers public async Task<IActionResult> Index(int page = 1) { var qry = _context.Suppliers.OrderBy(p => p.CompanyName); var model = await PagingList<Suppliers>.CreateAsync(qry, 10, page); return View(model); } 28
  • 28. • • public void ConfigureServices(IServiceCollection services) { // Add framework services. ... services.AddMvc(); services.AddPaging(); • • @await Component.InvokeAsync("ReflectionIT.Mvc.Paging.Pager", new { pagingList = this.Model }) • • @await Html.PartialAsync("Pager", this.Model)
  • 29. 30
  • 30. @model ReflectionIT.Mvc.Paging.IPagingList @if (this.Model.PageCount > 1) { <ul class="pagination"> @for (int i = 1; i <= Model.PageCount; i++) { <li class="@((Model.PageIndex == i) ? "active" : null)"> @Html.ActionLink(i.ToString(), Model.Action, Model.GetRouteValueForPage(i)) </li> } </ul> } 31
  • 31. • // GET: Products public async Task<IActionResult> Index(string filter, int page = 1, string sortExpression = "ProductName") { var qry = _context.Products .Include(p => p.Category) .Include(p => p.Supplier) .AsQueryable(); if (!string.IsNullOrWhiteSpace(filter)) { qry = qry.Where(p => p.ProductName.Contains(filter)); } var model = await PagingList<Products>.CreateAsync(qry, 10, page, sortExpression, "ProductName"); model.RouteValue = new RouteValueDictionary { { "filter", filter} }; return View(model); } 32
  • 32. @model ReflectionIT.Mvc.Paging.PagingList<WebApplication2.Models.Products> @using ReflectionIT.Mvc.Paging; @*Brings SortableHeaderFor extension method into scope*@ @{ ViewData["Title"] = "Products"; } <h1>Products</h1> <p><a asp-action="Create">Create New</a></p> <form method="get" asp-antiforgery="false"> <div class="form-group"> <label class="sr-only" for="filter">Filter</label> @Html.TextBox("filter", null, null, new { type = "search", @class = "form-control", placeholder = "your filter" }) </div> <div class="form-group"> <button class="btn btn-primary">Search</button> </div> </form> @Html.Partial("Pager", this.Model) <table class="table table-striped"> <tr> <th>@Html.SortableHeaderFor(model => model.ProductName, "ProductName")</th> <th>@Html.SortableHeaderFor(model => model.Category.CategoryName, "Category.CategoryName, ProductName")</th> <th>@Html.SortableHeaderFor(model => model.Supplier.CompanyName, "Supplier.CompanyName, ProductName") </th> <th>@Html.SortableHeaderFor(model => model.QuantityPerUnit, "QuantityPerUnit") </th> 33
  • 34. • System.ComponentModel.DataAnnotations • Compare • • CustomValidation • • EmailAddress • • Range • • RegularExpression • • Required • • StringLength MaxLength MinLength • • Url • • • Remote • • 35
  • 35. public partial class Products { public Products() { OrderDetails = new HashSet<OrderDetails>(); } [Key] public int ProductID { get; set; } public int? CategoryID { get; set; } public bool Discontinued { get; set; } [Required] [MaxLength(40)] [MinLength(4)] public string ProductName { get; set; } [Range(1, 1000)] public decimal? UnitPrice { get; set; } [MaxLength(20)] public string QuantityPerUnit { get; set; } ... 36
  • 38. public class SuppliersController : Controller { public JsonResult IsCompanyNameAvailable(int? supplierId, string companyName) { if (!_context.Suppliers.Any(sup => (!supplierId.HasValue || sup.SupplierId != supplierId) && sup.CompanyName == companyName)) { return Json(true); } return Json($"{companyName} is already used"); } public partial class Suppliers { [Column("SupplierID")] [Key] public int SupplierId { get; set; } [Required] [MaxLength(40)] [Microsoft.AspNetCore.Mvc.Remote("IsCompanyNameAvailable", "Suppliers", "", AdditionalFields = "SupplierId")] public string CompanyName { get; set; }
  • 39. // POST: Products/Create [HttpPost][ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("ProductId,CategoryId,Discontinued,ProductName,QuantityPerUnit,ReorderLevel,SupplierId,UnitPrice,UnitsInStock,UnitsOnOr der")] Products products) { if (ModelState.IsValid) { _context.Add(products); //await _context.SaveChangesAsync(); if (await TrySaveChangesAsync()) { return RedirectToAction("Index"); } } ViewData["CategoryId"] = new SelectList(_context.Categories, "CategoryId", "CategoryName", products.CategoryId); ViewData["SupplierId"] = new SelectList(_context.Suppliers, "SupplierId", "CompanyName", products.SupplierId); return View(products); } private async Task<bool> TrySaveChangesAsync() { try { await _context.SaveChangesAsync(); return true; } catch (DbUpdateException ex) when ((ex.InnerException as SqlException).Number == 2601) { this.ModelState.AddModelError(string.Empty, "ProductName must be unique"); return false; } catch (Exception ex) { this.ModelState.AddModelError(string.Empty, ex.Message); return false; } }
  • 40. • DisplayAttribute • • DisplayFormatAttribute • • HiddenInputAttribute • • UIHint • • DataTypeAttribute • 41
  • 42. @{ string style = null; if (ViewData.Model < 20) { style = "color: red"; } if (ViewData.Model > 50) { style = "color: green"; } } <span style="@style">€ @(ViewData.Model?.ToString("N2"))</span>
  • 44. 45