Lee Naylor

ASP.NET MVC with Entity Framework and CSS

Lee Naylor

Newton-le-Willows, Merseyside, UK

Any source code or other supplementary materials referenced by the author in this text are available to readers at www.apress.com . For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ . Readers can also access source code at SpringerLink in the Supplementary Material section for each chapter.

ISBN 978-1-4842-2136-5

e-ISBN 978-1-4842-2137-2

DOI 10.1007/978-1-4842-2137-2

Library of Congress Control Number: 2016952810

© Lee Naylor 2016

ASP.NET MVC with Entity Framework and CSS

Managing Director: Welmoed Spahr

Lead Editor: Celestin Suresh John

Development Editor: Laura Berendson

Technical Reviewer: Fabio Ferracchiati

Editorial Board: Steve Anglin, Pramila Balan, Laura Berendson, Aaron Black, Louise Corrigan, Jonathan Gennick, Robert Hutchinson, Celestin Suresh John, Nikhil Karkal, James Markham, Susan McDermott, Matthew Moodie, Natalie Pao, Gwenan Spearing

Coordinating Editor: Nancy Chen

Copy Editor: Kezia Endsley

Compositor: SPi Global

Indexer: SPi Global

Artist: SPi Global

For information on translations, please e-mail [email protected] , or visit www.apress.com .

Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales .

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.

Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.

While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.

Printed on acid-free paper

Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springer.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.

I would like to dedicate this book to two special women in my life; my late mother Pauline, who sadly passed away while I was drafting the first few chapters, and my wife, Michelle. To Mum, thanks for always being there for me and I miss you every day, and to Michelle, thanks for all your support during difficult times, for giving me our wonderful son Peter, and for finding my best friend, our dog Chocky.

Introduction

I decided to write this book for people who learn by doing. I’ve read several software books over the years where you can read the whole book and learn many things but never quite put the full pieces of the jigsaw together. This book aims to allow the user to follow a step-by-step guide to learn how to use ASP.NET MVC with Entity Framework, while sticking to all the main topics you will encounter in everyday work scenarios, without focusing on academic details that very few people will ever use. I’ve tried to keep things relatively close to real life in the book, which is why I chose to make a baby store, but the examples can be applied to almost any type of shopping web site or indeed any web site driven by a database. I’ve also included a redesign of the site, including several popular CSS topics to recognize the fact that these days web developers need to be competent in front-end development too.

The book starts with an introduction to Microsoft ASP.NET MVC and then quickly progresses into showing you how to create a database driven web site, and from this how to enhance the site and use some of Entity Framework’s more advanced features. I’ll show you how to work with related tables and data, how to create and update a database schema, and how to populate data from your code.

I also cover how to use Microsoft Identity to add some user authentication and authorization to the site along with roles, and how to manage both of these. You’ll also learn how to deploy to Azure to allow your site run over the Internet.

The latter part of the book focuses on restyling the web site using CSS, with an introduction to jQuery thrown in, with the goal of this section being to get you up and running from basic to advanced CSS as quickly as possible.

The book mainly covers using ASP.NET MVC 5 with Entity Framework 6, which are the most widely used versions at the time of writing; however, it also includes an introduction to ASP.NET core and shows you how to create a basic web site and database.

The full source code for the examples shown in the book is available for download from http://www.apress.com .

Acknowledgments

I want to thank everyone I’ve worked with at Apress for their help in taking an idea and turning it into a reality. In particular, I want to thank Nancy Chen for keeping everything moving along, and to former Apress employee James DeWolf, for taking me on in the first place.

I’d like to thank my wife (again) for all her support and putting up with my lack of time and my day-dreaming about how to code something when she’s trying to have a real-life conversation with me about nappies.

Contents

  1. Chapter 1:​ Building a Basic MVC Web Site
    1. MVC and ASP.​NET MVC
    2. Entity Framework and Code First
      1. Using Code First with an Existing Database
    3. Software Required for Web Site Development
    4. Creating the Project
      1. Viewing the Web Site
      2. How the Home Page Works
      3. The About and Contact Pages and ViewBag
      4. Routing:​ How the Web Site Knows Which Controllers and Methods to Request
      5. The Purpose of the Layout Page
    5. Summary
  2. Chapter 2:​ Creating Views, Controllers, and a Database from Model Classes
    1. Adding the Model Classes
    2. Adding a Database Context
    3. Specifying a Connection String
    4. Adding Controllers and Views
      1. Adding a Category Controller and Views
      2. Examining the CategoriesContro​ller Class and Methods
      3. Examining the Category Views
      4. Adding a Product Controller and Views
    5. Using the New Product and Category Views
      1. Examining the Newly Created BabyStore Database
      2. Adding Some Data Using the Views
      3. Changing the Way the Category and Product Name Properties are Displayed Using DataAnnotations
    6. A Simple Query:​ Sorting Categories Alphabetically
    7. Filtering Products by Category:​ Searching Related Entities Using Navigational Properties and Include
    8. Summary
  3. Chapter 3:​ Searching, Advanced Filtering, and View Models
    1. Adding Product Search
      1. Updating the Controller for Product Searching
      2. Testing Product Search
      3. Adding a Search Box to the Main Site Navigation Bar
      4. How to Style Using Bootstrap
    2. Filtering the Search Results by Category Using ViewBag
      1. Updating the ProductsControll​er Index Method to Filter by Category
      2. Adding the Filter to the Products Index Page
    3. Using a View Model for More Complex Filtering
      1. Creating a View Model
      2. Updating the ProductsControll​er Index Method to Use the View Model
      3. Modifying the View to Display the New Filter Using the View Model
    4. Summary
  4. Chapter 4:​ More Advanced Data Management
    1. Deleting an Entity Used as a Foreign Key
    2. Enabling Code First Migrations and Seeding the Database with Data
      1. Enabling Code First Migrations
      2. Seeding the Database with Test Data
      3. Creating the Database Using the Initial Database Migration
    3. Adding Data Validation and Formatting Constraints to Model Classes
      1. Adding Validation and Formatting to the Category Class
      2. Adding Formatting and Validation to the Product Class
      3. How Validation Works
    4. Summary
  5. Chapter 5:​ Sorting, Paging, and Routing
    1. Sorting Products by Price
      1. Adding Sorting to the Products Index View
    2. Adding Paging
      1. Installing PagedList.​Mvc
      2. Updating the View Model and Controller for Paging
      3. Updating the Products Index View for Paging
    3. Routing
      1. Adding Routes
      2. Using Routes in Forms
      3. Using a Route in a Hyperlink
    4. Setting a Project Start URL
    5. Summary
  6. Chapter 6:​ Managing Product Images:​ Many-to-Many Relationships
    1. Creating Entities to Store Image Filenames
    2. Uploading Images
      1. Defining Reusable Constants
      2. Adding a ProductImage Controller and Views
      3. Updating the ProductImagesCon​troller Class for File Uploads
      4. Updating the View
      5. Testing File Uploads
      6. Checking for Unique Records Using Entity Framework
      7. Allowing Multiple File Uploads
      8. Working with the DbContext Object and Entity States
    3. Viewing SQL Generated by Entity Framework
    4. Performance Considerations When Using db.​SaveChanges()
    5. Dealing with Maximum Request Length Exceeded Errors
      1. Upping the Allowed Maximum Request Size
      2. Adding a Custom Error Page for Maximum Request Length Exceeded Errors
    6. Associating Images with a Product
      1. Adding a Many-to-Many Relationship with Payload
      2. Adding Images to a New Product
      3. Displaying Images in Search Results
      4. Editing a Product’s Images
      5. Deleting Images and Products
      6. Seeding the Database with Image Data
    7. Updating Image Editing, Details, and Index Views
    8. Creating a Partial View for Creating and Editing Products
    9. Summary
  7. Chapter 7:​ Authentication and Authorization Using ASP.​NET Identity
    1. Examining the Automatically Created BabyStore Project Identity Code and Database
    2. Working with Roles
      1. Adding a Role Manager
      2. Creating an Admin User and Admin Role Whenever the Identity Database Is Created:​ Using a Database Initializer
      3. Logging In as the Admin User
      4. Adding a Roles View Model and RolesAdminContro​ller
      5. Displaying All Roles
      6. Adding Authorization at a Controller Class Level
      7. Displaying Role Details
      8. Creating a Role
      9. Fixing the Navigation Bar Style Issues
      10. Editing a Role
      11. Deleting a Role
    3. Adding a Basic Admin Controller and View
      1. Adding Authorization to the Admin Controller and Admin Link
    4. Working with Users
      1. Adding Extra Properties for a User
      2. Working with Two Database Contexts:​ Updating the Identity Database for the New User Properties
      3. Updating the Admin User Creation Code for the New User Fields
      4. Creating a Users Role on Database Creation
      5. Adding a UsersAdminContro​ller
      6. Displaying All Users
      7. Displaying User Details
      8. Creating a New User as Admin
      9. Editing a User as Admin
      10. Dealing with Deleting Users
      11. User Self-Registration
      12. Allowing a User to View Personal Details
      13. Allowing Users to Edit Personal Details
      14. Allowing Users to Reset Their Passwords
      15. Managing Password Complexity
    5. Adding Authorization for Product and Category Administration
      1. Adding Authorization to Categories
      2. Adding Authorization to Products
    6. Improving Redirection after Logging In or Registration
      1. Redirecting Correctly After an Unsuccessful Then Successful Log In Attempt
      2. Always Redirecting to the Previous Page after Log In
      3. Always Redirecting to the Previous Page After Registration
    7. Summary
  8. Chapter 8:​ Creating a Shopping Basket
    1. Adding a BasketLine Entity
    2. Adding Basket Logic
    3. Adding a Basket View Model
    4. Adding a Basket Controller
    5. Adding a Basket Index View
    6. Allowing a User to Add to Basket
    7. Updating the Basket:​ Model Binding to a List or an Array
    8. Deleting a Line or Product from the Basket
    9. Displaying a Basket Summary
    10. Migrating a Basket When a User Logs In or Registers
      1. Migrating the Basket Upon Login
      2. Migrating the Basket Upon Registration
    11. Summary
  9. Chapter 9:​ Checkout:​ Creating and Viewing Orders
    1. Modeling Orders
    2. Creating Sample Order Data and Updating the Database
    3. Displaying Order Data
      1. Adding an OrdersController​ Class
      2. Displaying a List of Orders
      3. Displaying Order Details
    4. Placing an Order
      1. Creating an Order for Review
      2. Displaying an Order for Review
      3. Saving an Order to the Database
    5. Updating Product Deletion to Avoid Foreign Key Conflicts
    6. Adding Links to the Orders Index View
    7. Searching and Sorting Orders
      1. Orders Text Searching
      2. Searching Orders by Date
      3. Sorting Orders
    8. Summary
  10. Chapter 10:​ Advanced Scenarios and Common Workarounds
    1. Asynchronous Database Access
      1. A Simple Asynchronous Example:​ Adding Best Sellers to the Home Page
      2. Adding Asynchronous Paging
    2. Dealing with Concurrent Database Updates
      1. Warning Users When the Values They are Editing Have Been Changed by Another User
      2. Checking for Conflicts on Deletion
    3. Running Raw SQL Queries via Entity Framework
    4. Adding Custom Error Pages to the Site
    5. Common Entity Framework Problems and Workarounds
      1. Cannot Attach the File FilepathDatabaseName.​mdf as Database “DatabaseName”
      2. Code First Migrations Become Out of Order or No Longer Run Correctly
    6. Summary
  11. Chapter 11:​ Using Entity Framework Code First with an Existing Database
    1. Create a Database to Use with Code First
    2. Setting Up a New Project and Generating a Code First Data Model from the Database
      1. Setting Up a Controller and Views to View the Data
    3. Updating the Existing Database Using Code First Migrations
    4. Summary
  12. Chapter 12:​ Introduction to ASP.​NET Core v1.​0 (MVC6 and EF 7)
    1. Creating an ASP.​NET Core v1.​0 MVC Project
      1. Adding Product and Category Models
      2. Adding a Database Context
      3. Seeding the Database with Test Data
      4. Configuring the Connection String for the Database
      5. Configuring the Project to Use the SeedData Class and StoreContext
      6. Using Migrations to Create the Database
      7. Adding Controllers and Views
      8. Viewing the Data in the Web Site
      9. Correcting Bugs with the Scaffolding Generated Code
    2. Summary
  13. Chapter 13:​ Deploying to Azure
    1. Preparing to Deploy to Azure
      1. Changing from Using a Database Initializer to using a Code First Migrations Seed Method
      2. Setting Up Azure
    2. Deploying to Azure from Visual Studio
      1. Configuring Database Publishing
      2. Redeploying Code Changes to Azure
    3. Remote Debugging an Azure Web Application
    4. Viewing and Editing an Azure Database with Visual Studio
    5. Connection Resiliency When Using Azure
    6. Summary
  14. Chapter 14:​ Restyling the Web Site:​ An Introduction
    1. CSS:​ The Basics
      1. Styles
      2. Stylesheets
      3. Selectors
      4. Inheritance
      5. Cascading
      6. The Box Model
      7. Putting It Together:​ Visualizing the Box Model
    2. Updating the BabyStore Site to Use Your Own Stylesheet
      1. Using a CSS Reset
      2. Adding Basic Formatting
      3. Fading In Each Page
    3. Summary
  15. Chapter 15:​ Styling the Home Page
    1. Styling the Footer
      1. Using Line Height to Vertically Align Text
      2. Rounding Corners
    2. Styling the Home Page Headings by Using Font Weights and em Values for Font-Size
    3. Introducing Float for Displaying Images Next to One Another
      1. Using Clear After a Floated Element
    4. Styling the Images
    5. Basic Link Styling
    6. Styling a Hyperlink to Look Like a Button
    7. Removing an Element from the Page Flow Using CSS
    8. Summary
  16. Chapter 16:​ Styling Forms, Grid Layouts, and Tables
    1. Styling the Categories Index Page
      1. Adding Space Between Table Cells
      2. Styling the Links
    2. Styling the Category Edit Form
      1. Adding Vertical Space Using Margins
      2. Adding a Grid Layout
      3. Styling Labels and Text Boxes
      4. Revisiting the Grid System:​ Adding Blank Columns Using Margins
      5. Styling Buttons
      6. Styling the Cursor
      7. Styling Error Messages
    3. Styling the Other Forms in the Site
      1. Forcing Inheritance
      2. Aligning Text
      3. Box-Sizing
      4. Vertically Aligning Something with Another Element Containing Text
    4. Styling Definition Lists
    5. Styling Tables
    6. Styling the Paging Links
    7. A Sibling Selector Example:​ Styling the Create New Links
    8. Summary
  17. Chapter 17:​ Advanced CSS
    1. Styling the Navigation Bar
      1. Transforming the Navigation Bar Content to Display Horizontally
      2. Moving Elements Using Positioning
      3. Styling Text
      4. Adding Images Using CSS
      5. Floating Elements to the Right
      6. Adding Animation to Links Using Scaling
    2. Introducing jQuery
      1. How the Project References jQuery
      2. jQuery Syntax
      3. Using jQuery to Update the Main Image in the Product Details Page
    3. Summary
  18. Chapter 18:​ Responsive Web Sites:​ Styling for Mobile/​Cell and Tablet Sized Devices
    1. Introducing Media Queries
    2. Designing a Responsive Site
    3. Developing for Mobile/​Cell Using Google Chrome
    4. Making the Home Page Responsive
    5. Styling the Navigation Bar for Mobile/​Cell
      1. Showing/​Hiding the Navigation Bar
    6. Selectively Adding Columns
    7. Displaying Tables on Smaller Screens
    8. Viewing a Visual Studio Project on Another Device
    9. Summary
  19. Index

About the Author and About the Technical Reviewer

About the Author

A419071_1_En_BookFrontmatter_Figb_HTML.jpg

Lee Naylor is a software engineer from Manchester in the United Kingdom with expertise in programming and Agile project management. He spends his free time with his family, playing football (soccer) and golf.

About the Technical Reviewer

Fabio Claudio Ferracchiati is a senior consultant and a senior analyst/developer using Microsoft technologies. He works at BluArancio S.p.A ( www.bluarancio.com ) as a senior analyst/developer and Microsoft dynamics CRM specialist. He is a Microsoft Certified Solution Developer for .NET, a Microsoft Certified Application Developer for .NET, a Microsoft Certified Professional, and a prolific author and technical reviewer. Over the past 10 years, he’s written articles for Italian and international magazines and co-authored more than 10 books on a variety of computer topics.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset