SlideShare ist ein Scribd-Unternehmen logo
1 von 45
Downloaden Sie, um offline zu lesen
•
•
• C#
•
• ASP.NET MVC XAML
Windows 8 + 10
•
• MS SQL Server
•
• Trainer Developer
• www.reflectionit.nl
3
•
•
•
•
•
•
•
•
4
•
•
•
•
•
•
•
•
• 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
• 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
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
@{
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>
45
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framework core

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicBadoo Development
 
Александр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия SwiftАлександр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия SwiftCocoaHeads
 
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
 

Ähnlich wie 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
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magic
 
Александр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия SwiftАлександр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия Swift
 
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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 

Kürzlich hochgeladen (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

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

  • 1.
  • 2.
  • 3. • • • C# • • ASP.NET MVC XAML Windows 8 + 10 • • MS SQL Server • • Trainer Developer • www.reflectionit.nl 3
  • 5.
  • 6.
  • 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
  • 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
  • 36.
  • 37.
  • 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
  • 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>
  • 43.
  • 44. 45