Building Modern Websites 
with ASP.NET 
Rachel Appel 
http://rachelappel.com 
rachel@rachelappel.com
Agenda 
• Overview of ASP.NET MVC 
• Models 
• Controllers 
• Routing & REST 
• Views 
• ViewModels
ASP.NET MVC 
• Models 
• Views 
• Controllers 
• ViewModels
ASP.NET MVC Overview 
• ASP.NET implementation of MVC 
• MVC Pattern 
• What about other patterns? 
• MVVM Pattern, MVW, or MV* Patterns 
• Routing 
• RESTful
Models 
• The application’s data 
• Expressed in code as classes and their members 
• Contains relationships 
• Mapped to database objects
Models 
namespace Bakery.Models 
{ 
public class Category 
{ 
[Key] 
public int Id { get; set; } 
public string Name { get; set; } 
public virtual ICollection<Product> Products { get; set; } 
} 
}
Models 
namespace Bakery.Models 
{ 
public class Product 
{ 
public int Id { get; set; } 
public string Name { get; set; } 
public string Description { get; set; } 
public string Image { get; set; } 
public decimal Price { get; set; } 
public DateTime ExpirationDate { get; set; } 
public int QuantityOnHand { get; set; } 
} 
}
Entity Framework 
• Entity Framework 
• Code First 
• Database First 
• Model First 
• DbSet<T> 
• Database Initializer (Code first) 
• DBContext
Entity Framework 
public class BakeryContext : DbContext 
{ 
public DbSet<CartItem> CartItem { get; set; } 
public DbSet<Order> Order { get; set; } 
public DbSet<OrderDetail> OrderDetails { get; set; } 
public DbSet<ShoppingCart> ShoppingCart { get; set; } 
public DbSet<Category> Category { get; set; } 
public DbSet<Product> Products { get; set; } 
}
Entity Framework 
In the global.asax.cs file 
System.Data.Entity.Database.SetInitializer( 
new Models.DBContextInitializer());
Entity Framework 
public class DBContextInitializer : DropCreateDatabaseAlways<MyContext> 
{ 
protected override void Seed(MyContext context) 
{ 
// fill db 
} 
}
Controllers 
• Match.com for Models and Views 
• Traffic Cop 
• Perform routing 
• Accepts HTTP requests 
• Front door of application 
• Security
Controllers 
namespace Bakery.Controllers 
{ 
public class ProductsController : Controller 
{ 
private BakeryContext db = new BakeryContext(); 
public ActionResult Index() 
{ 
return View(db.Products.ToList()); 
} 
} 
}
Controllers 
• HTTP POST Data & HTTP Verbs 
[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Edit(Product product) 
{ 
if (ModelState.IsValid) 
{ 
db.Entry(product).State = EntityState.Modified; 
db.SaveChanges(); 
return RedirectToAction("Index"); 
} 
return View(product); 
}
Routing / RESTful URLs 
• REST : Representational State Transfer 
• Request resources via RESTful URL
URLS 
Not RESTful 
http://books.com?isbn= 978-1500712952 
http://shopping.com?category=2&subcategory=3 
RESTful 
http://books.com/classics/jane-eyre 
http://shopping.com/computers/laptops
/products/ 
/product/index 
/products/details/cupcake 
/products/create 
/products/edit 
/products/delete/cupcake 
public class ProductsController : Controller 
{ 
public ActionResult Index() {...} 
public ActionResult Details(string? name) {...} 
public ActionResult Create() {...} 
[HttpPost] 
public ActionResult Create(Product product) {} 
public ActionResult Edit(string? name) {...} 
[HttpPost] 
public ActionResult Edit(Product product) {...} 
public ActionResult Delete(string? name) {...} 
}
Routing 
public class RouteConfig 
{ 
public static void RegisterRoutes(RouteCollection routes) 
{ 
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
routes.MapRoute(name: "Default", 
url: "{controller}/{action}/{id}", 
defaults: new { controller = "Home", 
action = "Index", 
id = UrlParameter.Optional }); 
} 
}
Routing 
protected void Application_Start() 
{ 
RouteConfig.RegisterRoutes(RouteTable.Routes); 
}
Views 
• The UI/Presentation layer 
• Renders a model or ViewModel 
• Does not contain business logic 
• A visualization of data 
• Expects data from one source: a model or ViewModel 
• Use HTML Helpers or custom HTML
Views 
• Helpers 
• Links 
• Controls
Convention over Configuration 
• Controller and action method name 
• Matches the URL
Views 
@model IEnumerable<Bakery.Models.Product> 
@foreach (var item in Model) { 
<tr> 
<td>@Html.DisplayFor(modelItem => item.Name) </td> 
<td>@Html.DisplayFor(modelItem => item.Description) </td> 
<td><img src=@Url.Content("~/Content/Images/")@item.ImageName alt="Image" 
/></td> 
<td>@Html.DisplayFor(modelItem => item.Price) </td> 
<td>@Html.DisplayFor(modelItem => item.QuantityOnHand) </td> 
<td>@Html.ActionLink("Edit", "Edit", new { id=item.Id }) | 
@Html.ActionLink("Details", "Details", new { id=item.Id }) | 
@Html.ActionLink("Delete", "Delete", new { id=item.Id }) 
</td> 
</tr> 
}
Views and JavaScript Libraries 
• Included in VS 2012/2013 Project Templates 
• jQuery & jQuery Mobile (2012) 
• jQuery 
• Bootstrap 
• Modernizr 
• Respond.js 
• You can use any 3rd party JS library in MVC views
Scaffolding 
• Quickly create controllers and views based on models
ViewModels 
• A representation of one or more models 
• Formatted & polished data 
• UI logic code to format data 
• One single ViewModel object per view 
• Promotes SOC (Separation of Concerns)
ViewModels 
public class CustomerViewModel 
{ 
public Customer Customer { get; set; } 
public StatesDictionary States { get; set; 
} 
public CustomerViewModel(Customer customer) 
{ 
Customer = customer; 
States = new StatesDictionary(); 
} 
}
Sumary 
• Models, Views, Controllers

More Related Content

PPTX
Building Real Time Applications with ASP.NET SignalR 2.0 by Rachel Appel
PPTX
ZZ BC#7.5 asp.net mvc practice and guideline refresh!
PPTX
ASP.NET - Building Web Application..in the right way!
PPTX
ZZ BC#7 asp.net mvc practice and guideline by NineMvp
PDF
.Net template solution architecture
PPTX
Asp.Net MVC 5 in Arabic
PDF
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
PPTX
Asp.Net Mvc
Building Real Time Applications with ASP.NET SignalR 2.0 by Rachel Appel
ZZ BC#7.5 asp.net mvc practice and guideline refresh!
ASP.NET - Building Web Application..in the right way!
ZZ BC#7 asp.net mvc practice and guideline by NineMvp
.Net template solution architecture
Asp.Net MVC 5 in Arabic
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
Asp.Net Mvc

What's hot (20)

PPTX
Sitecore MVC (London User Group, April 29th 2014)
PDF
MongoDB.local Berlin: App development in a Serverless World
PPTX
Learn AJAX at ASIT
PPT
ADO.NET Data Services
PDF
PPTX
Microsoft SQL Server 2008
PDF
[2015/2016] Local data storage for web-based mobile apps
PPT
Entity Framework Overview
PPTX
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
PPTX
SoCal Code Camp 2011 - ASP.NET MVC 4
PDF
Esri Dev Summit 2009 Rest and Mvc Final
PPTX
SharePoint 2010 Client-side Object Model
PDF
Introduction to Asp.net 3.5 using VS 2008
PDF
PPTX
ASP.NET Lecture 2
PPT
Introduction to ajax
PPTX
ASP.NET lecture 8
PPTX
Introduction to ajax
PPTX
Session 35 - Design Patterns
PPTX
Angular js for Beginnners
Sitecore MVC (London User Group, April 29th 2014)
MongoDB.local Berlin: App development in a Serverless World
Learn AJAX at ASIT
ADO.NET Data Services
Microsoft SQL Server 2008
[2015/2016] Local data storage for web-based mobile apps
Entity Framework Overview
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
SoCal Code Camp 2011 - ASP.NET MVC 4
Esri Dev Summit 2009 Rest and Mvc Final
SharePoint 2010 Client-side Object Model
Introduction to Asp.net 3.5 using VS 2008
ASP.NET Lecture 2
Introduction to ajax
ASP.NET lecture 8
Introduction to ajax
Session 35 - Design Patterns
Angular js for Beginnners
Ad

Similar to Building Modern Websites with ASP.NET by Rachel Appel (20)

PPTX
ASP.NET - Building Web Application..in the right way!
PPTX
MVC & SQL_In_1_Hour
PPTX
Simple mvc4 prepared by gigin krishnan
PPTX
ASP.NET MVC 5 - EF 6 - VS2015
PDF
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
PPTX
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
PDF
Django Rest Framework and React and Redux, Oh My!
PPTX
Asp.NET MVC
PPTX
Asp.net mvc training
PPT
MVC ppt presentation
KEY
Templates
KEY
Introduction Django
PPTX
Sitecore MVC: Converting Web Forms sublayouts
PPTX
Spring Web MVC
PPT
Introduction to ASP.NET MVC
PPTX
Getting started with MVC 5 and Visual Studio 2013
PPTX
Modern android development
PPTX
Asp.Net MVC Intro
PPTX
Practical OData
PPTX
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
ASP.NET - Building Web Application..in the right way!
MVC & SQL_In_1_Hour
Simple mvc4 prepared by gigin krishnan
ASP.NET MVC 5 - EF 6 - VS2015
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
Django Rest Framework and React and Redux, Oh My!
Asp.NET MVC
Asp.net mvc training
MVC ppt presentation
Templates
Introduction Django
Sitecore MVC: Converting Web Forms sublayouts
Spring Web MVC
Introduction to ASP.NET MVC
Getting started with MVC 5 and Visual Studio 2013
Modern android development
Asp.Net MVC Intro
Practical OData
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Ad

More from .NET Conf UY (17)

PPTX
Roslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
PDF
Machine Learning: Inteligencia Artificial no es sólo un tema de Ciencia Ficci...
PPTX
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
PPTX
Windows y .NET en la Internet of Things by Pablo Garcia
PPTX
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
PPTX
Metodologías ¿Ágiles o productivas? Una visión desde la trinchera by Marcos E...
PDF
Tips & tricks for sharing C# code on iOS, Android and Windows Phone by Jaime ...
PDF
Emprendiendo un futuro by Gabriel Camargo
PPTX
Microsoft Platform Vision by Eduardo Mangarelli
PDF
Arquitectura para Windows Azure: Pienso, luego existo by Fernando Machado
PPTX
Extendiendo SharePoint, Project y Office 2013 con el nuevo modelo de Apps by ...
PDF
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
PPTX
Opportunities to Improve System Reliability and Resilience by Donald Belcham
PDF
RESTful Para todos by Diego Sapriza
PPTX
Introduction to Aspect Oriented Programming by Donald Belcham
PPTX
Fun with .NET - Windows Phone, LEGO Mindstorms, and Azure by Dan Fernandez
PPTX
Azure: un parque de diversiones en la nube para el desarrollador moderno by A...
Roslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
Machine Learning: Inteligencia Artificial no es sólo un tema de Ciencia Ficci...
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
Windows y .NET en la Internet of Things by Pablo Garcia
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Metodologías ¿Ágiles o productivas? Una visión desde la trinchera by Marcos E...
Tips & tricks for sharing C# code on iOS, Android and Windows Phone by Jaime ...
Emprendiendo un futuro by Gabriel Camargo
Microsoft Platform Vision by Eduardo Mangarelli
Arquitectura para Windows Azure: Pienso, luego existo by Fernando Machado
Extendiendo SharePoint, Project y Office 2013 con el nuevo modelo de Apps by ...
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Opportunities to Improve System Reliability and Resilience by Donald Belcham
RESTful Para todos by Diego Sapriza
Introduction to Aspect Oriented Programming by Donald Belcham
Fun with .NET - Windows Phone, LEGO Mindstorms, and Azure by Dan Fernandez
Azure: un parque de diversiones en la nube para el desarrollador moderno by A...

Recently uploaded (20)

DOCX
search engine optimization ppt fir known well about this
PDF
STKI Israel Market Study 2025 version august
PPTX
Modernising the Digital Integration Hub
PDF
Getting started with AI Agents and Multi-Agent Systems
PPTX
The various Industrial Revolutions .pptx
PDF
Improvisation in detection of pomegranate leaf disease using transfer learni...
PDF
Enhancing plagiarism detection using data pre-processing and machine learning...
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PDF
Developing a website for English-speaking practice to English as a foreign la...
DOCX
Basics of Cloud Computing - Cloud Ecosystem
PDF
Comparative analysis of machine learning models for fake news detection in so...
PDF
Architecture types and enterprise applications.pdf
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PPT
Module 1.ppt Iot fundamentals and Architecture
PPTX
Custom Battery Pack Design Considerations for Performance and Safety
PDF
sbt 2.0: go big (Scala Days 2025 edition)
PPTX
Benefits of Physical activity for teenagers.pptx
PPTX
Build Your First AI Agent with UiPath.pptx
PDF
“A New Era of 3D Sensing: Transforming Industries and Creating Opportunities,...
PDF
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
search engine optimization ppt fir known well about this
STKI Israel Market Study 2025 version august
Modernising the Digital Integration Hub
Getting started with AI Agents and Multi-Agent Systems
The various Industrial Revolutions .pptx
Improvisation in detection of pomegranate leaf disease using transfer learni...
Enhancing plagiarism detection using data pre-processing and machine learning...
NewMind AI Weekly Chronicles – August ’25 Week III
Developing a website for English-speaking practice to English as a foreign la...
Basics of Cloud Computing - Cloud Ecosystem
Comparative analysis of machine learning models for fake news detection in so...
Architecture types and enterprise applications.pdf
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
Module 1.ppt Iot fundamentals and Architecture
Custom Battery Pack Design Considerations for Performance and Safety
sbt 2.0: go big (Scala Days 2025 edition)
Benefits of Physical activity for teenagers.pptx
Build Your First AI Agent with UiPath.pptx
“A New Era of 3D Sensing: Transforming Industries and Creating Opportunities,...
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...

Building Modern Websites with ASP.NET by Rachel Appel

  • 1. Building Modern Websites with ASP.NET Rachel Appel http://rachelappel.com [email protected]
  • 2. Agenda • Overview of ASP.NET MVC • Models • Controllers • Routing & REST • Views • ViewModels
  • 3. ASP.NET MVC • Models • Views • Controllers • ViewModels
  • 4. ASP.NET MVC Overview • ASP.NET implementation of MVC • MVC Pattern • What about other patterns? • MVVM Pattern, MVW, or MV* Patterns • Routing • RESTful
  • 5. Models • The application’s data • Expressed in code as classes and their members • Contains relationships • Mapped to database objects
  • 6. Models namespace Bakery.Models { public class Category { [Key] public int Id { get; set; } public string Name { get; set; } public virtual ICollection<Product> Products { get; set; } } }
  • 7. Models namespace Bakery.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public string Image { get; set; } public decimal Price { get; set; } public DateTime ExpirationDate { get; set; } public int QuantityOnHand { get; set; } } }
  • 8. Entity Framework • Entity Framework • Code First • Database First • Model First • DbSet<T> • Database Initializer (Code first) • DBContext
  • 9. Entity Framework public class BakeryContext : DbContext { public DbSet<CartItem> CartItem { get; set; } public DbSet<Order> Order { get; set; } public DbSet<OrderDetail> OrderDetails { get; set; } public DbSet<ShoppingCart> ShoppingCart { get; set; } public DbSet<Category> Category { get; set; } public DbSet<Product> Products { get; set; } }
  • 10. Entity Framework In the global.asax.cs file System.Data.Entity.Database.SetInitializer( new Models.DBContextInitializer());
  • 11. Entity Framework public class DBContextInitializer : DropCreateDatabaseAlways<MyContext> { protected override void Seed(MyContext context) { // fill db } }
  • 12. Controllers • Match.com for Models and Views • Traffic Cop • Perform routing • Accepts HTTP requests • Front door of application • Security
  • 13. Controllers namespace Bakery.Controllers { public class ProductsController : Controller { private BakeryContext db = new BakeryContext(); public ActionResult Index() { return View(db.Products.ToList()); } } }
  • 14. Controllers • HTTP POST Data & HTTP Verbs [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(Product product) { if (ModelState.IsValid) { db.Entry(product).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(product); }
  • 15. Routing / RESTful URLs • REST : Representational State Transfer • Request resources via RESTful URL
  • 16. URLS Not RESTful http://books.com?isbn= 978-1500712952 http://shopping.com?category=2&subcategory=3 RESTful http://books.com/classics/jane-eyre http://shopping.com/computers/laptops
  • 17. /products/ /product/index /products/details/cupcake /products/create /products/edit /products/delete/cupcake public class ProductsController : Controller { public ActionResult Index() {...} public ActionResult Details(string? name) {...} public ActionResult Create() {...} [HttpPost] public ActionResult Create(Product product) {} public ActionResult Edit(string? name) {...} [HttpPost] public ActionResult Edit(Product product) {...} public ActionResult Delete(string? name) {...} }
  • 18. Routing public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }); } }
  • 19. Routing protected void Application_Start() { RouteConfig.RegisterRoutes(RouteTable.Routes); }
  • 20. Views • The UI/Presentation layer • Renders a model or ViewModel • Does not contain business logic • A visualization of data • Expects data from one source: a model or ViewModel • Use HTML Helpers or custom HTML
  • 21. Views • Helpers • Links • Controls
  • 22. Convention over Configuration • Controller and action method name • Matches the URL
  • 23. Views @model IEnumerable<Bakery.Models.Product> @foreach (var item in Model) { <tr> <td>@Html.DisplayFor(modelItem => item.Name) </td> <td>@Html.DisplayFor(modelItem => item.Description) </td> <td><img [email protected]("~/Content/Images/")@item.ImageName alt="Image" /></td> <td>@Html.DisplayFor(modelItem => item.Price) </td> <td>@Html.DisplayFor(modelItem => item.QuantityOnHand) </td> <td>@Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id }) </td> </tr> }
  • 24. Views and JavaScript Libraries • Included in VS 2012/2013 Project Templates • jQuery & jQuery Mobile (2012) • jQuery • Bootstrap • Modernizr • Respond.js • You can use any 3rd party JS library in MVC views
  • 25. Scaffolding • Quickly create controllers and views based on models
  • 26. ViewModels • A representation of one or more models • Formatted & polished data • UI logic code to format data • One single ViewModel object per view • Promotes SOC (Separation of Concerns)
  • 27. ViewModels public class CustomerViewModel { public Customer Customer { get; set; } public StatesDictionary States { get; set; } public CustomerViewModel(Customer customer) { Customer = customer; States = new StatesDictionary(); } }
  • 28. Sumary • Models, Views, Controllers

Editor's Notes

  • #12: DropCreateDatabaseIfModelChanges
  • #16: good restful design https://blog.apigee.com/detail/restful_api_design_nouns_are_good_verbs_are_bad these resources are manipulated using HTTP requests where the method (GET, POST, PUT, PATCH, DELETE) has specific meaning. But what can I make a resource? Well, these should be nouns (not verbs!) that make sense from the perspective of the API consumer. Although your internal models may map neatly to resources, it isn't necessarily a one-to-one mapping. The key here is to not leak irrelevant implementation details out to your API! Some of SupportFu's nouns would be ticket, user and group. Once you have your resources defined, you need to identify what actions apply to them and how those would map to your API. RESTful principles provide strategies to handle CRUD actions using HTTP methods mapped as follows: GET /tickets - Retrieves a list of tickets GET /tickets/12 - Retrieves a specific ticket POST /tickets - Creates a new ticket PUT /tickets/12 - Updates ticket #12 PATCH /tickets/12 - Partially updates ticket #12 DELETE /tickets/12 - Deletes ticket #12 The great thing about REST is that you're leveraging existing HTTP methods to implement significant functionality on just a single /tickets endpoint. There are no method naming conventions to follow and the URL structure is clean & clear. REST FTW! from http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#restful
  • #20: protected void Application_Start() {     RouteConfig.RegisterRoutes(RouteTable.Routes); }