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 });
}
}
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
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
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();
}
}
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