You are on page 1of 61

Course Overview

Course Overview
(Music) Hi, this is Scott Allen, and welcome to my course on ASP.NET MVC 5. I've designed this course to give you everything
that you need to start working with the MVC 5 framework. In the course, we'll learn to use controllers and models and views with
ASP.NET. We'll also be using the Entity Framework as we learn how to read, write, delete, and update data while building an
application to manage restaurants. We'll also see how to enable features like client-side validation and add a few third-party libraries
to an application to make the application flexible and easier to maintain. By the end of the course, you'll be ready to work on your
own ASP.NET MVC application and move onto other courses here atPluralsight, courses that specialize in building APIs with the
MVC framework and testing and building single-page applications. Let's get started, and I hope you'll be using Visual Studio to
follow along.

Creating a New ASP.NET MVC Application


Understanding the ASP.NET Framework Options
Hi, this is Scott, and in this module we're going to start building our ASP.NET MVC application. I hope you'll follow along with
this module and throughout the rest of the course as we continue to add features in the application that we'll start in this module.
Throughout this course, I'm going to be using Visual Studio 2019, and everything that you need to complete this course you can get
with the Community Edition of Visual Studio 2019. The Community Edition is a completely free download from Microsoft. If you
do a search for download Visual Studio, you should be able to come to this web page, visualstudio.microsoft .com /downloads, and
from here you can click on the button to download this free Community Edition of Visual Studio. Of course, web pages and user
interfaces, they change all the time, so this page and this URL might look different when you're watching this video in the future.
But there should always be a way to download the free edition of Visual Studio 2019, theCommunity Edition. When you are
installing Visual Studio 2019, I want to call some attention to some specific options that you need to install. So I have
already installed Visual Studio 2019, but I'm going to open up the installation program that you can open up at any time, and
from in here I'm going to click on the Modify button to modify the installation. And I just want to show you that you want to make
sure that you select the ASP.NET and web development workload to install. So make sure that option is installed, and that should
install ASP.NET and the ASP.NET MVC framework. Now to be very specific about the framework that we're going to use in this
course, we are going to be using the ASP.NET MVC 5 framework. The version numbers around ASP.NET can be a little bit
confusing, but ASP.NET MVC 5 is part of the larger ASP.NET 4 framework. So this is version 5 of the MVC framework that ships
as part of ASP.NET 4. And this is the framework and the technology that we're going to be using in this course. Ifyou've heard of or
are aware of ASP.NET Core, then this is not the course for ASP.NET Core. I have another course covering ASP.NET Core that is
very similar to this course in that it teaches you the fundamentals. But we are going to be working with ASP.NET MVC 5. If you
want an overview of the differences between MVC 5, which is part of ASP.NET 4, and ASP.NET Core, Microsoft does have
some documentation out there. You can see that ASP.NET Core is completely open source, it works across platforms. And if you
want to develop on macOS or Linux, then ASP.NET Core is really the best option from Microsoft for that. On the other hand,
you might be working with an organization that is still using the ASP.NET 4 framework. And there are many of us that do
this. ASP.NET 4 includes ASP.NET MVC version 5, which we will be using. And it builds on top of the full .NET Framework. The
full .NET Framework allows you to take advantage of technologies like Windows Communication Foundation, WCF, as well
as ASP.NET Web Forms, and Web API and Web Pages. In this course, we're going to be building an application that accesses
data inside of a SQL Server database. I will show you how to work with models and views and controllers, the three words for
which the MVC framework is named. And along the way, I'm going to give you some best practices and some guidance and some
tips on how to most effectively use ASP.NET. To get started, the first step will be creating a project in Visual Studio. Let's take a
look at how to do that next.

Creating a Blank Solution


I have already installed and launched Visual Studio 2019. And here in the opening window, there is an option to achieve what I
want to do, which is create a new project. I'm going to click on that box and come to the screen where I can select one of the
templates available from a number of templates here for creating a project. And just so you know, you can filter these project
templates by language, platform, and project type. So if I know that I want to work with C#, and I only want to see C# projects, I
can select C#. And I could also set the project type to be a Web project type. That will be useful to know in just a minute. But for
right now, I want to select a special type of template known as the empty or blank template. So if you do a search for empty or
blank, you should be able to find an option for a Blank Solution. A solution file in Visual Studio 2019 will allow you to organize
one or more projects. What we're ultimately going to do for this application is create multiple projects. I'll talk about why you might
also want to have multiple projects. But anytime you have multiple projects, you'll probably want a solution file that can group and
organize those projects so you treat them as one solution, one application. We'll see how that works as we move throughout the
course. I want tostart with a blank solution that has no projects inside so I have complete control over where the projects are going
to live and where my solution file exists, I'm going to select Blank Solution and click Next. It's a little bit confusing because the next
screen will say Configure your new project, although technically we're not creating a new project yet, we're just creating a solution.
But again, this will give you complete control over how things are laid out on the file system. I want to create a project that is a
solution by the name of OdeToFood. What we're going to build is a simple application that will allow a user to view and edit
restaurants. Since we're oriented around food, this is going to be the OdeToFood project, theOdeToFood solution. I have a
specific location in mind for this project. It is under a GitHub folder, and I want to place it into a folder called odetofoodmvc.
You can select any location on your file system, but I'm storing it in a specific location where I keep my GitHub projects. And you'll
notice the solution name is going to be OdeToFood. When I click Create, this should open the Visual Studio IDE. And if I come to
the SolutionExplorer window, which is currently closed, I can click on this to open the window, I now have a solution, which
is OdeToFood. If for some reason you do not have a Solution Explorer window available, you can always go to the View menu
and click on Solution Explorer. The keyboard shortcut for this is Ctrl+Alt+L, but if I click on Solution Explorer, even if
this window is closed, it should open up. I can now pin this window so it always appears here on the right-hand side of the
IDE. And now that we have this blank solution ready to go, my next step will be to add a project into the solution. We'll do that in
the next clip.

Adding a Starting ASP.NET MVC Project


Now that I have a solution file, I can start to place projects into the solution. A project in Visual Studio and .NET is a place where I
can write my code and compile that code into something that I can run and execute or host in a web server. So the first project I
want to add to the solution is the project that will represent my web application. It will contain all the code that I need to respond to
requests from a browser or respond to requests from a client as part of an API, and return HTML, or JSON, or images, or
JavaScript, whatever I need to return from this web application. So let's right-click on the solution, and I want to say that I want to
Add a New Project. Once I select this option, this should open up a dialog that, again, we'll see this list of standard templates that
you can use in Visual Studio. And what I want to do is create a web project based on the C#language. So I'm going to filter by
the language type of C#, I'm going to select a project type of Web. And one of the templates that should come up here at this point
is the ASP.NET Web Application template. So I don't want to create an ASP.NET Core project, I cover this topic in a different
course, I want to create an ASP.NET Web Application that is built on the .NET Framework. I'm going to select that option and click
Next. And now I can fill out some information about my project. I want this project name to be OdeToFood.Web. So this is part of
the larger solution for OdeToFood. And the larger solution is a system and application that is designed to deliver restaurant
information to the end users. But this specific project represents the web UI portion of the solution. You might create a separate
project to host all the classes and code related to data accessfor your application. You might have a separate project for unit tests.
You might want to include a separate project that represents the domain or the business objects that are central to your application.
I'm going to stick with a relatively straightforward solution. I am going to create a dedicated project here for the web application,
and I'm going to place it underneath the OdeToFood directory and I'm going to use the latestversion of the .NET Framework, which
is version 4.7 .2. For the most part, there are no major changes planned for the ASP.NET MVC framework, so if you want to try
using a later, newer version of the .NET Framework, feel free to try that. But if you want to be as compatible as possible with the
code that I'm writing, you also might want to stick with .NET Framework 4.7 .2. I'm going to click Create. And now I can be a little
more specific about the type of ASP.NET Web Application that I want to create. So there are project templates in here that allow
me to create an empty application or an application based on ASP.NET Web Forms, which have been around and are part of .NET
since the very beginning of .NET.There's also the MVC project template, which is oriented towards building a web application that's
going to have a user interface. And that's slightly different from the Web API project. This also builds on ASP.NET Web
Application, but everything is a little more oriented towards buildingan API, so something that's going to send and receive JSON
and XML. You can add a user interface to a Web API project and you can add an API to an MVC project. So these choices aren't
entirely exclusive, but I am going to start with the MVC project. There's also an example of how to build a single-page application.
We'll take a look at some of these other project types later in the course, but right now we're going to build an MVC application.
I do want to configure this project for HTTPS, we're not going to start off with Docker support, but that is very easy to add later. I'm
just going to click Create, Visual Studio will need to think a bit, but eventually when this dialog completes back in Visual Studio
and the SolutionExplorer window, I should now have a solution and the OdeToFood.Web project. Inside of this project are a
number of folders that we will be talking about throughout the course. There's also .cs files, which represent the code behind this
application. And the first thing I'm going to do just to make sure that everything is working correctly is I'm going to go to the Build
menu and say that I want to build this entire solution. This will force Visual Studio to use the MSBuild tool to run the C# compiler
across all of the code here. And I can see that I have successfully built one project. It is built into what we call an assembly,
the OdeToFood.Web .dll assembly. So that contains compiled code from my application. And if you want more details about the
compiler and C#, then please go watch my C# Fundamentals course. But for now, the next thing I want to do is comeinto the Debug
menu and I want to start this application running without the debugger. I'm not really wanting to debug my application, I just want
to see it up and running in a browser. This did open a window on a separate monitor. So I'm going to drag that window over here.
You can see that I'm looking at a screen that says there's a potential security risk ahead. So here's what happens. ASP.NET and
Visual Studio try to set things up so that you can start developing with Transport Layer Security turned on, that is SSL or
HTTPS. And in order to do that, Visual Studio will add a certificate to your development web server, which IIS Express. And
this security certificate is self-signed. So most browsers will not recognize thecertificate as coming from a trusted source. Now
different browsers might have different screens here. And for some browsers, they will trust this certificate because it has been
registered in Windows as something to trust. But Firefox in particular is going to come back and say it has detected a potential
security threat. We can go into the Advanced menu and see that yes, this is a self-signed certificate, but that's okay. I do want
to work with this website, localhost, so I will say that I will accept the risk and continue on. When I do that, the browser will go
ahead and send off a request to localhost, and eventually, yes, fingers crossed, my application is up and running successfully. So
when you use the ASP.NET MVC template to create a new web project in Visual Studio 2019, you'll be given an application that
already has a home page, it already has an about page, it already has a page that shows contact information, it has all these little
features right out of the box. What we want to do is start building OdeToFood, that is going to be a website that displays
restaurant information. Let's take a first step towards that goal in the next clip and create a new project with the class inside that can
represent a restaurant.

Adding a Data Project


The goal for this module is to show restaurant data on the home page of the application. We're not going to talk to a database right
away, but I want to pretend or simulate how things will work when we talk to a real SQL Server database. In order to get that far,
I'm going to need classes that define the shape of the data that I want to query for in SQL Server and that I can use to place data onto
the home page. So I need a restaurant class that will hold restaurant data, and I need a service or component or an abstraction that I
can use to go out and pretend to query my SQL Server database for this restaurant information. Once we have those basics in place
and we learn a little bit more about how this framework behaves, then we're going to be able to drill into more detail in each of the
following modules, and also switch things over to work with a real SQL Server database. But to get started, what I want to do is
place my data-related abstractions into a separate project. Now there's nothing that says you need multiple projects to build a web
application. I could have this one project, OdeToFood.Web, and I could placeeverything that I need into this one single project, all
the code I need, as well as all the HTML and JavaScript and CSS and everything else that goes into a web project. But I also just
want to show you what it would look like if you decide to separate or break down a large application into smaller pieces and smaller
projects. What happens, for example, if I need to access my OdeToFood database from several different applications? Some people
would say you should only do that with services or microservices, but what if I have some small utilities that need to talk to
the database? In that case, it might help to place all of my data related abstractions into a separate project, and then I can share and
reuse that project among other applications. I can even take that project and publish it as a NuGet package so that other teams inside
of my own company can actually make use of that code. So what I'm going to show you is how to create another project and how
we can reference that project and use the abstractions inside of that project from our web application. So once again, right-click
on the solution, and I want to Add a New Project. This time, I am not looking for a web application, this time what I'm going to look
for is a Class Library. So I'm not trying to build an application that standsalone and can execute. I'm trying to build a library that can
be shared and reused across multiple projects. So I'm going to pick Class Library built on top of the .NET Framework and then click
the Next button. So this will allow me to write C# classes that I can share amongst multiple projects. We will name this
project OdeToFood.Data. We will place it as a subfolder of OdeToFood, and once again we will use .NET Framework 4.7 .2. I'm
going to click Create, and Visual Studio has added an additional project to my solution. Inside of this project, it has given me a
starting class, Class1.cs, I don't need that class, so I'm going to delete that class. Instead, we're going to add a class to represent
restaurant information. And we will do that in the next clip.

Adding a Model Restaurant


For the data project, there are actually at least two different categories of abstractions that I want to add to this project. One of those
categories would be the category that would hold all of the classes that define the shape of my data, that would include classes like
a restaurant class to hold restaurant information. But also in this project, I want to add some abstractions that represent the services
or the components that I will use to access data. And since I have these two different categories, it would be nice to place those two
different types of abstractions into two differentnamespaces, which in .NET and C# programming means I should use some folders
to categorize my type. So let's add a folder. Let's call it Models. This represents my business objects or my domain model or the
entities or the information, essentially, that I want to store in a database. We're not going to cover a specific style of
programming here, like domain-driven development or task-driven development. Those are topics that are covered in other courses.
But I do want to store restaurant information in the database and query for restaurant to display restaurant on the home page, so
I will need a class to represent a restaurant. Let's add a class to this folder. And let's call it Restaurant.cs. The template I just used
when Iright-clicked and said that I wanted to add a new item, I selected the Class template. I could have also right-clicked and said
that I went to just add a class, I would select that template right away. This gives me a basic .cs file with some common namespaces
already included. It also gives me an internal class which I cannot use outside of this project. But since I will need to use this class in
the web project, let me go ahead and add a public modifier to this class so I can use it outside of the OdeToFood.Data project. And
now let's describe some of the attributes and some of the state that should be stored for each restaurant. Every restaurant will be
stored in a SQL Server database, and SQL Server likes to give entities or each record that's in a table a primary key. So let's create
a property using the prop code snippet, which is p-r-o-p, and I can just press Tab to expand that into an auto-implemented property
in Visual Studio. Let's create an integer property named Id. So I just need to type p-r-o-p, hit Tab, and then I can Tab between the
name and the type of this property. So another property I might want to add would be a string property that can hold the name of the
restaurant. Now there's all sorts of interesting information that we could store about a restaurant. We could store the location, we
could have relationships defined in our database, so every restaurant has a collection of employees, every restaurant has a collection
of menus, there's the lunch menu, there's the dinner menu, we could really build out quite a sophisticated model. But for this
course, I'm going to keep things very simple. I'm going to give you all the concepts that you just need to apply to keep adding
more complexity into an application. But we're going to stick with a relatively simple definition for a restaurant, we'll store the Id
and the name, and perhaps let's choose one other thing just to make itinteresting. Let's store the cuisine type of a restaurant. So I
could add another String property and name that property Cuisine. And this will represent a column in the database that allows
pretty much free form text entry. You can enter anything that you want as a cuisine. But what if we wanted to restrict the
possible values of cuisine? Well, one way, just one approach you can use to do that is to define an enum in C#. Let's do that.
I'm going to right-click on the Models folder again and I want to add another new item. Again, I'm going to select Class for the type
of item that I want to add. And we are going to add a new type, the CuisineType. This will generate an internal class, but I'm going
to change this to a public enum instead. And then the members of our enum, let's start with a None, so this represents a
restaurant that does not have a specific cuisine, orperhaps it's an unknown cuisine. And then let's just pick a few easy cuisines out
of the hundreds of available cuisines in the world. Let's just say Italian, there's Indian, and there's French. And if we come back to
Restaurant, I can now change this to be a type of CuisineType. And this willdefine the model that I want to use for a restaurant. It
will define what I want to show on the screen, as well as what I want to store in the database. More on this type of model later in the
course, but for right now, let's move to the next clip and define some components or someabstractions that we can use to query a
data source of restaurants.

Adding an In-memory Data Source


What I want to do is add an abstraction that will simulate data access to a SQL Server database. Later in the course, we will be using
a SQL Server database, but I want to show you how easy it can be to switch between in-memory data that I just put together really
quickly to put something on the screen, and then change over to using SQL Server later in the course. To do that, I want to hide
the real source of data access behind aninterface definition. So let's first add a new folder to the OdeToFood.Data project. I will
name this folder Services, so these will be services and components to perform data access. And in the Services folder, let's Add,
and this time I'm going to select New Item and I'm going to selectInterface instead of class. Let's call this IRestaurantData. I'm going
to go ahead and add this interface definition to the project. And I do want to point out that the approach that I am using is just one
approach of many different approaches that you could use to solve this problem. So I'm not showing you the one true way, what I'm
showing you is one possible solution. So we have this interface, IRestaurantData, I'm going to change it tobe a public interface
because I do plan on using this interface definition outside of the OdeToFood.Data project. And now I can start thinking about the
different operations that I want to perform on the data source. Eventually, we're going to need the ability to update and edit
and delete restaurant. But to get started, again, the simplest case is I just want a list of all the restaurants that are in my data source. I
don't want to worry yetabout paging and some of those other operations when there's a lot of restaurants in the database. I just
want to a list of all the restaurants. So let's start with a method that will return an IEnumerable of Restaurant, so multiple restaurants.
In order for this to work, I'm going to need to use Ctrl+period in Visual Studio and tell Visual Studio to bring in the namespace,
OdeToFood.Data .Models, I'm going to select that option. That is the return type for my method. And let's name the method GetAll.
In other words, give me all the restaurants. Inside of the same class, inside of the same file, let me go ahead and add a class, which is
InMemoryRestaurantData. It's going to implement the interface IRestaurantData. And it's going to be a public class, and as you'll
see in just a moment, it's going to be very easy for me to move this class definition into its own file. But before I do that, let me
go ahead and hit Ctrl+period on the interface. So I just need to place my cursor here on the interface, there's a red squiggly
underneath it, if I press Ctrl+period, Visual Studio will implement this interface for me, which means it will add all the methods and
other members that need to be present on this class. And I just need to fill in the implementation. Before I do that, let me place the
cursor on the class identifier,InMemoryRestaurantData, and hit Ctrl+period. Now Visual Studio offers me a refactoring operation to
move this type, InMemoryRestaurantData, to its own file InMemoryRestaurantData.cs, that just follows a convention that most C#
and Visual Studio developers will also follow, which is that every type gets its own dedicated file, and the position of that file
relative to the project and folder hierarchy will determine the namespace andthe name of the class. So, InMemoryRestaurantData.cs
will be the file that has a class by the same name. And since the class lives in the Servicesfolder of the OdeToFood.Data project, it is
in the namespace, OdeToFood.Data .Services. Let me go ahead and select this option to move this type. And I now have my
InMemoryRestaurantData.cs file here. So let's think about how we can implement GetAll. Again, I just want to start with the
simplest possible solution. So let's define some InMemoryRestaurant, so literally a list of restaurants. So I'm going to need a List
type, a list ofRestaurant. And we can make this a private field that is named restaurants. And then let's add a constructor to this class.
So I can use the ctor code snippet, press Tab, Tab, I now have a default constructor for InMemoryRestaurant and I can say
that restaurants equals a new List ofRestaurant, and then use a collection initializer to start adding restaurants into this list
immediately. Let's add a restaurant with an Id of 1. Let's set the name equal to Scott's Pizza. And since this is pizza, let's also set the
cuisine to a CuisineType of Italian. I'm going to copy and paste that line so I don't have to type as much, and then just change a few
things around to add restaurant number 2. Let's call this Tersiguels. This is a little place that I know near my hometown, and its
CuisineType is French. And let me paste one more time, this time we'll have the restaurant of 3, I'll change the name, let's call this
one Mango Grove, and set the CuisineType to Indian. So I now have an InMemoryRestaurantData class that when it is constructed
will instantiate a new list of restaurants and populate that list. And I do want to point out that this would never work in production, it
would never work in a real web application, just storing the data in memory, but it does work in development and testing, and just to
get started. Again later in the course, we'll come back and store these restaurants in a real SQL Server. Now the implementation of
GetAll, all I really need to do is just return that list of restaurants because a list of restaurants does implement the interface,
IEnumerable of Restaurant. But just to simulate what we might want to do in a real data access component, let's go ahead and throw
in an OrderBy operation. I do need to use Ctrl+period to bring in the namespace, System.Linq, because what I'm using is
the OrderBy extension method from the System.Linq namespace. But I can say given a restaurant r, please order by the restaurant
name. So the restaurant should come out ordered by name in ascending order. So we shouldn't see the restaurants listed as 1, 2, and
3, we should actually see Mango Grove come out first, as long as the other components in the applicationdon't change that ordering.
We will see that shortly once we start building the UI. But before we can build the UI, we have to figure out where to place the
code that can respond to a request that arise for this home page of the application.

Responding to HTTP Messages from a Controller


In this clip, we're going to get right into the essence of the ASP.NET MVC framework. And if you feel like this clip is going too
fast, don't worry, we're going to spend the rest of the course diving into some of the details around the concepts and techniques that I
show you in this clip. Because what we need to do in this clip is respond to a request for the root of the website. So localhost port
and some port number. I need to respond to this request. And ultimately, what I want to do is display a list of all the restaurants that
I know about in our database, which is an in-memory database. And what we will discover is that in the Model-View-Controller
framework, you have a model, you have a view, and you have acontroller, and it is the controller's responsibility to figure out how
to respond to a particular request. So when a request arrives for /Home/Contact, what piece of software is responsible for saying, oh,
I know what I need to do, I need to show the Contact page. Likewise, when a request arrives for /Home/About, what piece of
software, what class, what piece of code has to execute, and say that the appropriate response is to display the application
description page. And when I'm on the Home URL, the root URL, just localhost port 44388/, what is the combination of
components that determine that this is the appropriate response? Well, the first thing I want to show you is that there's always a
controller behindthe scenes, the controller, which starts with C, which is part of the MVC framework. The C stands for
controller, and it is the controller that isresponsible for determining what to do with this request. So if I come back into Visual
Studio, I will see there is a Controllers folder, and inside of this folder there is a class named HomeController. Like I say, we'll
be diving into more details later in the course, we're going to figure out exactlywhat are the rules that direct that request to this class.
But right now, I just want to show you that inside the HomeController there is a method on this class named Index. And ultimately,
a request for the home page of the application to the root of the application is going to invoke this Index method. Currently, it is
returning a view, which starts with V, and that's the V in the MVC framework, Model-View-Controller. I'm going to change this,
just temporarily, and say that I want to return, just a simple string, we're going to return the text, Hello, World, with an
exclamation point. Only this doesn't work because the return type of this method is of type ActionResult. So let me also
temporarily tell the C# compiler that this method just returned a string. And this is going to be legal code, I'm going to do a build in
the project. So Shift+Ctrl+B is the keyboard shortcut in Visual Studio 2019 to do a build. And because I am running the application
without a debugger attached, remember, I started without the debugger, as long as my web server is still running, I should be able to
come to the browser, and now that I've rebuilt the application, I can just refresh and I can see the updated code. The updated code
says to respond with just Hello, World. And that's because this request from the browser arrived at this method. So one way
to respond to a request is just to return a string, and the string could include HTML markup if I wanted to use this approachwhere I
write HTML inside of my C# strings. But that's not a very pleasant solution. It's very difficult to write HTML correctly when you're
just inside of a string literal in the C# language. And that's why we have these special files known as views. So instead of returning
a string, I'm going to return what happens when I invoke the view method that is a member of this HomeController. I'm going to
change the return type back toActionResult. And I will tell you that when I return View from a controller method, the MVC
framework is going to go looking for a specific file in a specific folder to find the HTML that I want to render into the browser or
render into the response when this method is invoked. And again, all of this is covered in more detail throughout the rest of the
course. But if I go to the Views folder, this is, by default, where all the views associatedwith my application will reside. And when I
render a view from the HomeController, the framework will look in a Home folder. And when I render a view from the
Index method of that particular controller, the framework is going to look for a file, index.cshtml. So, cshtml is the extension for a
Razor view with the MVC framework. And as the extension implies, this file can be a combination of HTML markup and C# code,
little C# expressions. So right now everything that you see here, like the text, ASP.NET is a free web framework, if I come back to
the browser, ASP.NET is afree web framework, you might remember that was part of a text that was displaying in the browser
before I made that change to the HomeController. In fact, now that I have changed this back to rendering a view, let me just do a
another Shift+Ctrl+B to rebuild the project andlet's come back into the web browser and refresh, and we should now be looking
at the results of what happens when the MVC framework renders this view, index.cshtml. And what I want to do is instead
of returning a string from my controller action, let me just replace some of thetext that is inside of here, I'll just add a simple div and
now say, Hello, World. But now I'll be in some properly formatted HTML. And in fact, everything else inside of index.cshtml, I'm
going to delete for right now. I need to save that file. I'll also do a build just in case and refresh the browser, and I can now see
Hello, World. This is displaying inside of a Bootstrap jumbotron. So Bootstrap is a CSS framework that helps us present our
HTML and modify the layout and the colors. And because, back in my Razor page, because I am in a div that has a class of
jumbotron,Bootstrap is going to apply some special styles to this text to make it appear like what you're seeing here. But what if
this is not the text I want to display? What if I want to display a list of all the restaurants that I know about? Well, in that case, I need
the M from MVC. So when my controller is deciding what to do, when it's deciding that it needs to render a view, it also needs to
build a model. And that model is going to contain all theinformation that my view needs to complete its job. Let's look at how to
build a model inside of this controller in the next clip.

Building the Model


If the home page of our application needs to display a list of all the restaurants in the database, then our HomeController Index
method needs to build a model that carries all that information about the restaurants into the view, because this is the essence of the
separation of concerns that is a part of the Model-View-Controller design pattern. The controller is responsible for receiving
a request and deciding what to do next. Do I render a view, do I render a string, do I render XML or JSON? The controller here
is making a decision to render a view. The view is only going to care about presentation, the view is not allowed to do data access,
it's not supposed to be calling web services. Instead, the controller is responsible for building a model, the model's going to contain
all the information that the view needs to present. And then the controller hands that model off to the view. The model doesn't know
anything about the controller, the model doesn't know anything about the view, it doesn't know if it's going to be presented as JSON
or XML or placed into an HTML document. The model is simply there to transport the data and logic related to the business. So we
have the controller receiving a request and building a model, the controller hands things off to a view, which is responsible for
presenting that information. In order to make all this work, my controller is going to need an InMemoryRestaurantData component
to be able to fetch and build a model. So let's go ahead and add a private field to our HomeController. We will make this of type
IRestaurantData, which means I need to do two things in order to access that interface. First, I need to add a reference from the
OdeToFood.Web project to the OdeToFood.Data project. If you haven't worked with C# before, references tell the C# compiler
where to look when it's trying to resolve symbols. So where does IRestaurantData come from? Well, it's not an interface that is
defined as part of the .NET Framework and it's not part of this project, so we have to tell the C# compiler by adding a reference, and
I can do that here in Visual Studio by pressing Ctrl+period and selecting the option to add a reference to OdeToFood.Data. Or, I can
also do that over here if I right-click on the project and say that I want to Add, and down here in the context menu select Reference.
When I add a reference, I can select from Assemblies that might be in the global assembly cache or on disk, I can browse to any
assembly. You can see I already have some references here to assemblies like Microsoft.CSharp. But what I want to do is reference
aproject, another project that is in the same solution. So I'm going to go to the Projects tab, and I'm going to select OdeToFood.Data.
Once I bring in that assembly reference, it will be listed here as one of the references in my project. You can see there's many others.
And then I just need to add a using statement for the namespace so that the C# compiler can now find that type, IRestaurantData.
I'm going to do that using Ctrl+period in Visual Studio and just selecting using OdeToFood.Data .Services. So this is the type of our
private field, and let's just call the field, we'll give it a name of db. Because ultimately, this is how I want the controller to think
about the database, so it's going to access the database through this interface, IRestaurantData. We will also give our controller a
constructor to initialize this field. So I want this to be a new instance of InMemoryRestaurantData. Now later in the course, I'm
going to show you a much better approach for retrieving an object that implements the IRestaurantData interface. But right now
we're going to do the simplest possible thing, which is simply to construct a new instance of a concrete type, the
InMemoryRestaurantData type. And we're going to place that into a field in the controller, and we're just going to start using it.
Later in the course, I'll show you how you can add a lot of flexibility to your MVC applications by avoiding the new keyword, and
instead using a technique known as dependency injection. We'll get to that later. For right now, I have something that implements
IRestaurantData, it's available to my controller, and I'm going to use it to build a model. My model will simply be what happens
when I ask my data source to give me all the restaurants that are in the database. That is now my model, and I'm going to pass this
model into the view. Here's how to think about this. When I invoke the View method, this is a method that I inherit from my base
controller class. And it's something that I can invoke to produce an ActionResult. AnActionResult, in general, tells the
MVC framework what to do next. So once we're finished with this Index method, what should the MVC framework do next? Well,
it should render a view. It's going to render the default view for the Index action of the HomeController, which means it will be the
index.cshtml view that's in the Home folder of the Views folder. That's what's going to happen. And when the MVC framework
goes out to index.cshtml to render this view and figure out what HTML to produce, we are going to pass along an object that
represents the model, and thatobject in this case is going to be an IEnumerable of Restaurant. Let's see how to use that model and
put it to use in the next clip.

Rendering the Model


If I told you that this index Razor view receives, as a model object, a collection of restaurants to display, then your first question
might be, how do I use my model object inside of this view, inside of this syntax that you're showing me? Well, of course, I'm going
to give you many more details and tips about Razor views as we move throughout this course. But for right now, I just want to
demonstrate how easy it is to move and transition between literal text and HTML markup and writing C# code. So when I use the at
sign, that will transition the Razor engine from HTML markup mode into C# expression mode. And if I write a C# expression here,
then at runtime, the Razor engine can evaluate that expression and output the result into the response. In other words, if I write
a simple C# expression, like DateTime.Now .Year, and then I save this index.cshtml view and I come back to the browser and I do
a refresh, I can see that, yes, I am recording this, and currently it is the year 2019. So back in Visual Studio, when I need to display
dynamic information, so something that is not just static text, like writing out the div as part of my HTML or writing out the word
ASP.NET, when I need something dynamic, I can switch over into C# mode and I can inspect something about my model object
and output it anywhere I want inside of this HTML. So that's the first thing to know about Razor views. The second thing to know
about Razor views is that when I use the at sign and I'm writing C# code, I can access properties that are part of the object that is
this view. One of those properties is named Model with an uppercase M, so @Model. That is accessing the model object that the
controller has given to this view. Now I know that the controller is passing this view a collection of restaurants, I know I have an
IEnumerable of Restaurant. Unfortunately, Visual Studio and the Razor View Engine, they do not know that model is going to be
an IEnumerable of Restaurant, not yet at least. We'll solve that in just a minute. But let's pretend that the first thing I want to do is
just write out the text that says, there are x number of restaurants in the database, whatever x is. In that case, I might create a div
here inside of the jumbotron. And I can do that by typing div, that's like a shortcut, and then pressing Tab that will expand out to
give me my opening div tag and my closing div tag. And inside of here, I can say there are x number of restaurants in the database.
How do I make x dynamic? Well, again, I'll write some sort of expression here with C# and use the at sign. Ultimately, I'll be able to
go directly tothe model. But for right now, I just want to show you that I can invoke a method on the Enumerable class that is part of
the .NET Framework, I can invoke a method named Count. And I can pass in this model property that is available to my view.
So all I'm trying to do is say how manyrestaurants I know about in the database, or how many restaurants do I have in my model.
And I can do that by writing the C# expression using Enumerable.Count and passing in my model object, which is an enumerable.
So once again, if I save that view and come back out to the browser and refresh, I can now see there are three restaurants in the db.
Perhaps that's not the best English sentence in the world. So let's just change that around now that I'm seeing it, we'll just say there
are x restaurants in the database. But now let me also show you that I can tell Visual Studio and the Razor engine, and I can tell
everybody that this model object I am receiving, it has to be of type IEnumerable of Restaurant. I can do that by using what's known
as a Razor directive. It's a little bit confusing because a directive also starts with an at sign. But in this case, I'm going to use
alowercase m and say @model. And what I'm going to do is tell a Razor View Engine the type of the model it should expect
to receive. The type of that model is going to be IEnumerable, and it's going to be of type OdeToFood.Data .Models .Restaurant. So
for right now inside of a Razor view,I'm going to use the full type name including the namespace. Later, I'll show you how you can
shorten this. But this first line here is known as a model directive, @model, lowercase m. And it is telling everybody that the type of
model this view expects to process is of type IEnumerable of Restaurant. And once I do that, when I come to my model
property, this model property should be typed as IEnumerable of Restaurant. You can see that over here in the IntelliSense
window. I'm now working with IEnumerable of Restaurant. So now what I should be able to do is invoke a Count method that
is available for IEnumerable through the magic of extension methods and the System.Linq namespace. We'll talk about how that
namespace gets involved here later. But the big picture here is that I have a model object I'm receiving from my controller, I can
access that model object through the model property of this view, which I can get to once I use the at sign. And I can type that
property using the @model directive. So now once again, I'm going to save and come back and refresh. And I should still see the
text, There are 3 restaurants, but now my model object is a little bit easier to work with. So how do I create a list of all the
restaurant names that I know about, let's say? Perhaps I want to put my list of restaurants in a ul, an unordered list, and each
restaurant name will go inside of a list item. Well in that case, once again, I can rely on the fact that I can write C# code and I can
write a foreach statement. So I can say foreach restaurant that you find in the model property, I want to do the following. And this is
a really good demonstration of how you can mix C# code and HTML inside of a Razor view. Because when I use the at sign,
the Razor View Engine knows to transition into C# mode, and what's it going to do in C#? Well, it's going to set up a loop.
And inside the body foreach loop, what I want to do is write out a list item. And at this point inside of here, I now have access to a
local variable namedrestaurant, but what I'll be doing is I'll be creating a list item for each restaurant that is in the model. So if I have
three restaurants, I'll be creatingthree list items. And since I have access to a local variable now, restaurant, I can also use
@restaurant and create an expression that writes out the restaurant name. And you can see just how easy it is to transition from
literal text in HTML into a C# expression or a C# statement using the at sign. But the Razor parser's also pretty smart and it knows
when to transition out of C# mode and back into HTML and literal text mode. So it knows that angle bracket /li here is probably not
a piece of C# code that I want to evaluate, that's probably HTML, and the Razor engine just does the right thing. So now if I save all
my files, save my view, come back to the browser and refresh, I should now see a list of those three restaurants that we put together
as the model object in my controller. And what you've just witnessed is really just the essence of the MVC framework. And
the majority of the rest of this course is just going to be going into the finer details of how to work with the MVC framework. And
we're going to see more views, which are responsible for presenting the model object. It's the controller that puts together that
model object. And the controller will typically do that using services and components that you give to it, it's going to use those
to build a model and select a view to render. But as we'll see, a controller can also make some other decisions. So it can decide to
deny access to a particular section of the application, it can decideto redirect to another URL. The controller really is in control of
what happens when a particular request arrives for the application. Now that we have this overview of the MVC framework, let's
wrap up this module and move to the next module where we will start building upon what we've learned here and learn about how
this application is put together.

Application Startup and Configuration


Understanding ASP.NET Hosting
Hi, this is Scott, and in this module we're going to see how an ASP.NET MVC application comes to life and how we can influence
the behavior of our application using configuration files. Understanding how the application starts up and where the application
retrieves configuration settings is important if you want the application to behave the way you would expect. I'll show you these
configuration files, and by the end of the module I have a couple of goals I want to achieve. The first goal is to understand
the configuration system just well enough to display a message on the screen, a custom message from a configuration file.
The second goal is to avoid hard coding our dependency on an InMemoryRestaurantDatasource. We'll remove that code that
we added in the last module that hard coded a dependency and replace the code with something more flexible. Before we get started
moving toward those goals, I think it's important to understand how we go from Visual Studio to delivering HTML inthe browser. It
all starts with the project that we are working with, OdeToFood.Web. This web project contains files of many different types. There
are configuration files so you can see in the graphic that just appeared there's a Packages.config and there's a Web.config. We'll talk
more about those configuration files here in a bit. But there's also .cs files, so files containing C# source code. That code needs to be
compiled before we can do anything interesting with that code on .NET. And there's also many other different types of files. So
there are script files inside of the Scripts folder. Those files can be JavaScript that we want to execute on our site. They could also
be JavaScript libraries like jQuery. There's also going to be images and CSS style sheets, and even CSS frameworks like Bootstrap.
And any time we do a build in Visual Studio, Visual Studio understandshow to compile these files and work everything together
and place everything into a directory where my project can execute as a web application. So the primary output of OdeToFood.Web
is going to be an assembly named OdeToFood.Web .dll. That's just a convention where the name of the assembly will be the same
as the project. but it will have that .dll extension that is so common in Windows. So this file contains executable code.
Well, technically, it contains code that has been compiled from C# code and is now in the Microsoft Intermediate Language format.
But that is executable code because .NET, the runtime, understands how to execute and process MSIL, Microsoft Intermediate
Language. But this file has no capability of starting on its own and then listening for socket connections that contain HTTP requests
from a web browser. That requires some web server infrastructure. So any time I tell Visual Studio to run my project, Visual
Studio has to produce this .dll, if it doesn't already exist, and then start up a web server that will host this .dll and map incoming
HTTP requests and send them along to this .dll. So the web server that Visual Studio will use is either IIS or IIS Express. IIS stands
for Internet Information Services. This is the web server that is provided by Windows andWindows Server. You can install IIS as
a component whenever you install Windows Server or Windows. But you can also rely on IIS Express, which is a slightly lighter
weight version of IIS installed for you by Visual Studio so that you can host and run web applications and at least serve up requests
that are coming from the local machine. And this is what happens when I tell Visual Studio to run my application either with the
debugger or without the debugger. By default, Visual Studio will be loading my assembly into IIS Express, and then I will have
the ability to point a browser to my localhost, IIS Express, and make a request to my application that retrieves some HTML. Or in
the situations where I'm building an API, perhaps I'm fetching JSON or XML instead of HTML, but it is still HTTP messaging
behind the scenes. There's an HTTP request, my application produces the HTML response, and IIS provides the hosting
infrastructure so that my application can execute. And if I come over here into Visual Studio, I just want to show you again if you
start without the debugger, Visual Studio will launch a browser. It's going to go to the IIS Express website where my application
is running. In this case localhost port 44388 was selected as the location for my application. And I will know if this isIIS Express
just by going to the taskbar in Windows. If I come into the system tray, this is a list of all of the little icons that are running in my
system tray, and you should find one for IIS Express. If I right-click IIS Express, it will show me all the websites it is
currently hosting. Right now there's only one, and that is my application, OdeToFood.Web. I can click to go to either the HTTP or
the HTTPS version of this application or I could stop this site altogether. If I do that and refresh the browser, I will find that I can no
longer connect to this application. So I have to get this application running again, and I can do that by coming into Visual Studio
and saying that I want to start without the debugger. Again, I usually run without thedebugger because any time you start with the
debugger, at some point if you stop the debugger, perhaps to rebuild an application, that's going to shut down the web server for you
behind the scenes and then you have to start everything running again. If you start without the debugger, you can make changes in
Visual Studio, you can rebuild and simply come out to the web browser and just hit Refresh, and anything new, any changes that
you made should be reflected in the browser's user interface. So now we know that my application produces an assembly,
OdeToFood.dll. That assembly is loaded into IIS Express, or if you are in production it's going to be loaded into IIS, and from there
we can start to process requests like this request to the home page because IIS is forwarding these requests, these HTTP messages to
my application. But how doesASP.NET know where to go when it receives a message that wants to reach the
resource /Home/Contact? Let's talk about that a little bit next.

Starting up an ASP.NET Application


There's a few magic conventions that exist in .NET and ASP.NET, and once you know these conventions they won't seem
so magical anymore. But every ASP.NET application will have a file with the name Global.asax. And this file really represents your
application, and it's from this file where you can define what happens at application startup. First of all, I want to show you the real
contents of Global.asax. I'm going to right-click and I'm going to say that I want to view the markup for this file, because as
we're about to discover, Global.asax really does look like more of a markup file than anything else, and here is markup that
is describing an application. It is our application. And this markup is saying that there is a Codebehind file, that is, there's some C#
source code sitting behind this file and that code is in Global.asax .cs. And the most important piece here though is the Inherits
attribute, which is telling ASP.NET, it's telling the runtime when you go to run this application, the first thing that you need to do
isinstantiate a class, which is the OdeToFood.Web .MvcApplication class. Where is this class defined? Well it just so happens this
class will be defined in this Codebehind file. Now, I bring all of this up in great detail not because you need to remember to type this
every time, it's just going to be created for you when you create a new project in Visual Studio. But all you really need to remember
on a day-to-day basis is that when you'reworking with an MVC application, when you need to look at the startup logic for
your application, the file to look for is the Global.asax .cs file. Inside of here, you will find one or more methods that can hook in to
the application lifecycle events of this HttpApplication class. One of the significant events in the life of an HTTP application is
when this application starts up. So what we're describing inside of the Application_Startmethod is all of the code and all of the logic
that we want to execute when this application starts up. I'm going to come back later in the course and describe exactly what is
happening with this AreaRegistration and this FilterConfig where we're trying to register global filters. I'm also in this module going
to go into more details about what happens when we register routes. But for right now I just want to show you that most of thiscode
that is being invoked is code that exists in the App_Start folder of this project. So if I open that folder, I will see there's a
BundleConfig, aFilterConfig, and a RouteConfig. These are all static methods that are being invoked from this Application_Start on
the HttpApplication. So let's look at, for example, RegisterBundles on the BundleConfig class. If I open this up, what I'm going to
discover is some configuration related to the bundling of JavaScript and CSS files. We'll talk about this later in the course when we
talk about client-side programming with ASP.NET MVC. But the simplified quick version is that this application is going to try
to bundle and minify scripts to make files as small as possible and to have as fewdownloads as possible in the client browser. And
ultimately, if the browser makes a request to the root of the website and then /Content/css, what the browser should receive is a
single file, a single download, that contains all the contents of bootstrap.css plus all the contents of the site.css file. Both of those
should exist in this Content folder. So bundling is simply the act of taking this bootstrap.css file and this site.css file, combining
them together and then trying to minify them, which you're probably aware of that term if you've done any web programming.
Minification is just tryingto make that download as small as possible by removing any unnecessary characters from those files. So
things like unnecessary whitespace can be removed so that the browser receives the style sheets, the style information as quickly as
possible. And these are the types of operations that are being configured during the startup of our application. So inside of
Global.asax .cs, we have an Application_Start method that will tell this BundleConfig class to register the bundles, and what it does
is work with the ASP.NET runtime and this BundleCollection class to define the bundles and the URLs that they will respond to.
So, responding to /Content/css with the bundle that includes both bootstrap.css, as well as mysite.css file. And that's going to
happen behind the scenes. So if we go back to the browser, let's make a request for /content/css, and the response that eventually
appears is going to contain bootstrap.css plus site.css, and it's not going to look pretty because it's been minified, which means a lot
of the line breaks and whitespace and comments have been removed. So that bit of configuration might explain how a request
to/Content/css behaves, but again, how does a request to /Home/Contact behave? How does that reach a piece of C# code or Razor
View that defines the HTML that appears here? That's what we're going to look at next when we return to Application_Start and
look at our route configuration.

Defining Routes for ASP.NET


The process of mapping an incoming URL, like localhost port 44388/Home/Contact, mapping this to a piece of software that we
have written to produce HTML is a process known as routing. So whenever we talk about routing or defining routes, we're talking
about some configuration that tells ASP.NET how to find a piece of software that can respond to a given URL, like /Home/Contact,
or even a request to localhost some port number slash, that is a request to the root of a website. ASP.NET also has to route this
request to some software component that can produce the appropriate HTML response, which in our case we wanted to show a list
of all the restaurants that are in the database. In order for that to happen, we have to tell ASP.NET how to process URLs and
map URLs to components that contain the C# code or the Razor code that we want to execute, and that is what happens inside of
RouteConfig.RegisterRoutes. If we open up the RouteConfig file, this contains the RouteConfig class and the static method, which
is RegisterRoutes. We are given from the MVC runtime an object known as the RouteCollection, and what we want to do isadd
routes into that RouteCollection that tell ASP.NET MVC what to do with a given request. This first piece of information is telling
ASP.NET MVC to ignore certain types of routes. And what follows is a route template that MVC will try to use to match an
incoming URL. So what this routetemplate is saying is that if you see a URL arriving, like the URL / trace.axd /1/2/3/4, try to take
that URL and see if it matches this template. So inside of a template, anything that is inside of curly braces becomes a parameter. So
that means MVC would be looking for something .axd, and indeed this URL contains .axd. So the MVC framework would say well
so far that part matches, and what we'll do is treat resource, we'll treat that parameter, that piece of data, as the word trace
because that's what was in this position at the URL. And then we're going to look for anyadditional path info. So the star is like the
wildcard character when you're doing a file search. It's saying match anything essentially, match anything and place it into a
parameter, a route parameter, known as pathInfo. And since we have the wildcard match here, /1/2/3/4, that would all go into
pathInfo. But what we're telling the MVC framework is to essentially ignore this route. Don't do anything. It turns out there's a
special URL endpoint built into every ASP.NET application that allows you to retrieve special tracing information, and that route is
always something .axd, and then it can contain some additional information in the URL. What's important to us in day-to-day
business programming is the MapRoute API. This is what you'll be using 99% of the time with ASP.NET MVC. This is the route
template that we will be using for the majority of building ourapplication. What we're telling the MVC framework is that here's a
new route, give it the name Default, and this is the URL template for this route. So we have a placeholder for a parameter
named controller, and we have a placeholder for a parameter named action, and then we have a placeholder for a parameter named
id. And that means if we receive a request like /home/contact, what MVC should do is treat home as the value of the
controller parameter, and it should treat contact as the value of the action parameter. And then if there is an additional piece
of information here, that is a third segment in the URL, take that third segment and treat it as a parameter named id, and this is
exactly what we're trying to do with the ASP.NET MVC framework. You might remember I said that controllers are responsible for
receiving some external stimulus. So, controllers are responsible for receiving HTTP requests, and what we're trying to do here is
we're trying to map URLs to controllers that are defined in our system. And when we say here that the controller parameter value is
home, because we have the URL /home/contact, that is telling the MVC framework to go off looking for something that is
named HomeController. So literally this value, home, followed by the word controller, and indeed inside of our application we
do have a class that is named HomeController. So a request to /Home/something is going to try to reach something in
this HomeController. It just so happens that /home/contact, this contact is treated as an action, so the name of the action is going to
be the name of the method that is invoked on this controller. So this is like saying I want to invoke on the HomeController a method
named Contact, and indeed if I flip over to HomeController I will see there is a Contact method here. So hopefully you're starting to
see how this can come together. And then there's one piece of additional information that we can include in the route, which is an id.
But it just so happens this id is considered optional, so I do not need an id in the URL in order to reach an action on a controller. It's
strictly optional. And what is this piece that I'm looking at here? This is part of an anonymous type which contains the defaults for
this route. So essentially what this anonymous type is doing is providing the values thatASP.NET MVC can use if a value for
a particular segment here is not provided by the URL. In other words, if there is no id, that's okay because the id is optional. What
happens if there is no action? What happens if I receive a request to just /home? In that case, let's try this, if I go to just /home, I
will receive the Index action of the home controller. So it is the Index action that is displaying a list of restaurants. And since there is
also a default provided for the controller value, if I go just to the root of the website, provide no other information, I will effectively
be executing the index method of the home controller. So these routing templates are how we tell the MVC framework to route
a given URL to a specific piece of software that will tell the MVC framework what to do next. So we want to route into methods on
our controller classes. And what happens if I want to process a URL like /greeting? Currently if I try to go to /greeting, I will receive
a 404 error from the ASP.NET MVC framework because theASP.NET MVC framework doesn't see any component that can
respond to /greeting. It's going to go looking for a greeting controller. It's not going to find one. So it just returns a 404. But what
happens if we right-click on the Controllers folder, say we want to add a new controller, andI'm going to create an empty MVC
5 controller. I'm going to create an empty controller and click Add, and I just will call this the GreetingController. Now again, more
details on controllers throughout the rest of this course, for right now I want to add something that will give a simple response if I
make a request to /greeting on this application. And the simplest possible thing I could do is just return a view from the
Index action. So remember this Index action, it is the default action if I did not specify an action in the URL. So if my URL is
only /greeting, I have a controller parameter value from the URL, I have no action, the default action will be Index. Therefore,
a request for /greeting should reach this Index method on the GreetingController. And what do we want to do? We want to return a
view. I will need to create this view because a view doesn't exist as yet. If I just right-click inside of that method, say that I want to
add a view, Visual Studio can be pretty smart and say oh, you must want to create a view named index in the appropriate location,
and I will say yes, let's do that. We're going to leave the template empty without a model. We'll talk more about what the different
templates are. For right now I'm just going to click Add. I'm going to have a RazorView appear or I can just saysomething like
Hello with an exclamation point, and now if I rebuild my project, Shift+Ctrl+B, come back to the browser, refresh, and send off
another request for /greeting, then I can see I've been successful. I've added a controller that can respond to /greeting. It renders
a view, index.cshtml, that displays the text Hello, and we've just added a little bit to our application.

Configuring ASP.NET with web.config


In addition to the configuration that you can find inside of the C# source code files, configuration files like RouteConfig and
FilterConfig andBundleConfig, there's also some XML-based configuration that goes into every ASP.NET and every IIS
application. One of the most significant sources of XML configuration is a file known as Web.config that will exist inside of your
project. If we open up Web.config, we're going to see a lot of settings that can influence the behavior of this application. Some of
the settings that are in here are setting up binding redirects. Binding redirects are a way to tell the runtime when you go looking
for this assembly, what you should do instead is actually find this other assembly with a different version perhaps. There's a number
of these binding redirects that exist in this Web.config file. For the most part they are uninteresting to us and we don't need to debug
or troubleshoot. They're simply provided when we say File, New Project inside of Visual Studio. There's also some configuration
for the compilers. This section is saying that we compile .cs files with the C# compiler, and .vb files with the Visual Basic compiler.
We don't need to worry about this section either. There's also some sections that tell ASP.NET what the target framework should be.
In this case we're going to use the .NET Framework version 4.7 .2, and there is also this generic appSettings, which is a section
where we can place pretty much any setting that we want. And many of the settings that are already here are settings that
influence specifically the ASP.NET MVC framework. So flags like UnobtrusiveJavaScriptEnabled and ClientValidationEnabled,
we'll talk about those later in the course when we start talking about client-side programming. But we can also turn features of
ASP.NET on and off using some special app settings that are in this file,specifically Web Pages, which we're not going to talk about
in this course. But what I do want to do is show you how you can add your own custom app setting and use that app setting from
inside the application. Because most nearly every real application is going to need some amount of configuration. You need to
tell an application what database to use or what message queue to use. You need to provide the address for some other web service
that the application needs to use. All of those pieces of information are likely candidates for this Web.config file. And let's say that I
wanted to add a new app setting, so every app setting has a key and a value. The key is what you use to identify a particular setting.
So let'ssay that we want to use a key of message. This is where I will store a custom message that my application is going to use. So
not just the text Hello, which we're currently displaying in the browser, I want this value provided by the configuration file not hard
coded into a view. So inside the configuration file let's say that the value should equal Have a great day, and I will save
this Web.config file, and let's make use of this configuration value from our GreetingController. Now what I want to do again is
make use of the Model-View-Controller framework. So I want my controller to receive an incoming request, a request for /greeting,
and I want my controller to render a view, but I also want my controller to build a model that will contain the information that that
view needs to render. So I want to build a model that is specific to this index view for the GreetingController.It's what some people
would call a view model because it's going to be a class whose only purpose in life is to carry information from this controller into
that view. Let's go into the Models folder and right-click and say that we want to add a class, I will call this the GreetingModel, or
the GreetingViewModel. Either name would be fine. I will say I do want a class, let's click Add to add this. And for right now let's
just give this viewmodel a single property. The property will be the Message to display. So again, technically I could find
that configuration value that I'm looking forin Web.config. I could find and retrieve this value from inside of the code that I place
into a Razor view. But ideally, if you follow the true spirit of the MVC design pattern, your view will not do any work to find or
filter data. Instead, all the data that this view needs will be provided by the controller, the GreetingController. So if I save this
view model, ultimately what I want to happen is that the GreetingController will build a model that is an instance of that
view model. So let's instantiate a GreetingViewModel, and yes, I do want to instantiate this, so let's use the new keyword, and let's
go ahead and bring in the namespace, so Ctrl+period, I need to bring in the namespace using OdeToFood.Web .Models. Now I can
say that the model.Message equals, and again I could hard code a value, but what I want to do is pull that value out of my
configuration file. All we need to do to retrieve that setting is go to a class known as the ConfigurationManager. I do need to
bring in the namespace, which isSystem.Configuration, and the ConfigurationManager is going to have a static property, which is
the AppSettings property, that will give me access to all my app settings like a dictionary. So in other words, if I index into
this collection using the same key that I have specified in Web.config, so the key would be Message, then I should be able
to retrieve the value for that app setting, and that's going to be my message. I'm going to pass that model into my view. So we saw
this in the previous module. I have a controller that renders a view. It passes along a model. The view it renders is in the Views
folder. It's in a folder that has the same name as the controller, so the Greeting folder, and the file name is the same as the action
name or the method name, which is Index. So we can open up Index and remember we can get to the model using at and then
uppercase M,Model. That goes to the model property, and that will be dynamic by default. But we can strongly type that property
using an @model directive, so at with a lowercase M. So I want to go to OdeToFood.Web .Models and specify
the GreetingViewModel as the type of my model, and now I should be able to write out Model.Message. And we will add
an exclamation point at the end. Let me save everything and do a quick build. We'll come back into the browser and refresh, and we
are now displaying that bit of information that we retrieved from the configuration file. But we retrieved that value using our
controller, not by going there directly from the view, and that's just to follow some of the best practices that the Model-View-
Controller design pattern tried to enforce.
Installing Autofac for Dependency Injection
We've now achieved the first of two goals that I mentioned at the beginning of this module. The first goal was to display a custom
message that we retrieved from a configuration source in ASP.NET. Now that we know how to do this, this is going to make things
a little bit easier in the future when we need to do things like configure a database connection string. But now let's try to address the
second goal. The second goal was to have some more flexible code here inside of the HomeController. I'm worried that we
have hard coded a dependency on the InMemoryRestaurantData class. I know for right now I'm just using this class to simulate data
access so that I can get some simple things done inside of the application without building out an entire database. But later I'm going
to want to switch over to using a database, and this is a somewhat common occurrence. Perhaps not this exact scenario where I'm
swapping between in-memory data and a real SQL Server database, but we always havescenarios in our applications where we want
to switch out one component for another. Perhaps that's to do unit testing, perhaps it's to do integration testing. Perhaps we want to
swap out a component that retrieves configuration information from a Web.config file with a component that retrieves
configuration information from a web service, let's say, or from a Redis cache. We always want this flexibility in our applications,
and this is the type of flexibility that the Dependency Inversion Principle can give you. If you haven't heard of the Dependency
Inversion Principle, that is the D in the SOLID design principles, and I'm sure you can find some courses here on Pluralsight about
SOLID design patterns and specifically the Dependency Inversion Principle. So I'm not going to go into a lot of details about this
particular design principle. I'm just going to show you how you can invert your dependencies in ASP.NET MVC, and how you can
rely on dependency injection to provide your controllers with the dependencies that it needs. So instead of hard coding that I need
the InMemoryRestaurantData here inside of my HomeController, I instead want to inject something that
implements IRestaurantData and simply let my HomeController depend on that object that implements this interface, it's going to be
given to me in the constructor. That way my HomeController doesn't have to have low-level knowledge of specific components like
InMemoryRestaurantData. I can just depend on the abstraction, which is IRestaurantData. In order to do this, I'm going to need what
is commonly referred to as a container, specifically an Inversion of Control container. Again, this is covered in other Pluralsight
courses, but an Inversion of Control container is something that knows how to build objects and how to analyze objects like
my HomeController to understand whatdependencies are required, and it's the container that can figure out what to inject when I
have a constructor that says please give me something that implements IRestaurantData, and then I can turn around and take
whatever is given to me and assign it into this private field forIRestaurantData. So currently if I try to do this, the MVC 5
framework does not come with a container that I can configure out of the box that will just know what to do about this
IRestaurantData. So now if I come to the home page of the application, instead of seeing a list of restaurants, Ishould receive an
error. And the error that the MVC runtime is giving me is that no parameterless constructor is defined for this object, where this
object specifically is that home controller. So the MVC framework is trying to activate a controller. It sees that there is
no constructor, there is a default constructor, that's a constructor that takes no parameters. The MVC framework has to pass
something in for IRestaurantData, and it doesn't know what to do. This is what an IoC container can do. If we tell the IoC container
to instantiate a HomeController and we configure the IoC container so that it knows what to do when something needs
IRestaurantData, then all of this can work. I'm going to show you how we can get this to work. In order to do that though we're
going to need a third-party component. There are many NuGet packages out there and open sourcelibraries that provide Inversion
of Control containers. Just a few off the top of my head would be Ninject, StructureMap, and the one I'm going to show you,
which is Autofac. Autofac is available as a NuGet package that I can download and install into this project, and then I can start
using it. So let's get that step out of the way first. I'm going to right-click on References and say that I want to Manage NuGet
Packages for this particularproject, and I'm going to do a search for Autofac, and I'm going to make sure that I have the Browse tab
installed when I do that search. And I can see the main Autofac package here, which is currently version 4.9 .2, but I'm going to
look for an even more specific Autofac package, which is the Autofac.Mvc5 package. So this not only contains the Autofac
package, but it's also going to provide what's known as an IDependencyResolverImplementation that will work with
System.Web .Mvc. So it will work with the MVC 5 framework. So although the MVC 5 framework doesn't come with a container,
it provides the right abstractions and the right hooks so it's very easy to place a container in charge of what the MVC 5 Runtime is
doing and what the MVC 5 Runtime is trying to create. So I'm going to select this package, Autofac.Mvc5, I'm going to
click Install. The NuGet Package Manager will go out and download this package. It's going to install that package into my
project, and now in the next clip what we need to do is add some startup code to configure Autofac and to plug it into the
MVC runtime so that we can get rid of this error message.

Configuring the Autofac Inversion of Controler Container


What we've seen so far in this module is that there are two types of configuration code in this application. The first type of
configuration code is configuration code that is in XML. So this is the type of code that's in the Web.config file. Here I can place
easy configuration settings, like the key value pairs that make up my application settings including my custom message. But there's
also configuration as code, and there's lots ofexamples of that with the MVC 5 framework. So, registering my routes is
something that I do with C# code, not XML. The same with filters and the same with bundles. What we need to do now is
configure Autofac, the container, as well as configure the MVC framework to use Autofac, and again, that is something I can
achieve through code so I don't have to write XML. What I'm going to do is add another config file here into theApp_Start folder.
So let me click Add. I want to add a class. And I want the name of this class to follow the spirit of the other files that are in this
App_Start folder, so we will call it ContainerConfig.cs. So we have BundleConfig, FilterConfig, RouteConfig, and
ContainerConfig, and I'm just going to change the namespace here. Although the convention in .NET and C# is to 99.9 % of the
time use a namespace that maps to the physical folder structure of your project, so it does make sense for this to be in the namespace
App_Start, but you'll notice in MVC 5 projects we typically don't use App_Start as part of a namespace. We just use
OdeToFood.Web. So inside of ContainerConfig I'm going to remove App_Start. It'll just be the namespace OdeToFood.Web with
the rest of these config classes. And the idea here is that inside of this class I'm going to have a method that I invoke from
Global.asax .cs, just like we do with FilterConfig, RouteConfig, and BundleConfig. The AreaRegistration is a little bit different and
it's a little bit more magical, but we'll come to that later in the course. Ultimately what I want to do is say ContainerConfig, please
register the container. And for this particular method call there's nothing in the MVC framework that I need to pass in. Instead, I
just need this method to exist on the class. It doesn't exist yet, but if I place my cursor here and press Ctrl+period, I can say that I
want to generate the methodContainerConfig.RegisterContainer. And now if I come back to my class definition, I have a
RegisterContainer method here. So what I'm going to show you now is essentially the Autofac API. So all of these different IoC
containers, StructureMap and Ninject and Autofac, they're all going to have a slightly different API, but the ultimate goal is to tell
the container about the different components and abstractions that you have in your project. So what are the services that you want
injected into other pieces of software inside of this application? That's what I need to tell the container so the container can
successfully resolve dependencies, and when it comes across something like the controller that is asking for IRestaurantData, the
container knows what to do. So first let's use the Autofac API and create something known as a ContainerBuilder. So as the
name implies, this is something that will build my IoC container. I'm going to use Ctrl+period and bring in the Autofac namespace,
because again, this is something that is specific to Autofac. So the idea of using dependency injection and having an Inversion of
Control container, those are all generic design patterns that are implemented by many different types of libraries, Autofac being just
one of those. So I need to build my containerbuilder and then I can start telling this builder about the different abstractions that are
in my application. The first thing I'm going to do is register my controllers. So this is a convenience method that if I spell it
correctly, I should have the ability to bring in the namespace. But if I type this correctly and hit Ctrl+period, I can bring in
the namespace named Autofac.Integration .Mvc because what I'm invoking is a custom extension method specifically designed
to integrate MVC 5 with Autofac. So what this is going to do is scan through my project for the different controller types
and register those with Autofac, so Autofac knows about all the different controllers that I have inside of my application, so the
GreetingController and the HomeController. All I need to do is tell Autofac what assembly contains the controllers for my
application. So I'm going to use typeof MvcApplication here, so just in case I'm skipping around too much and you're wondering
where the heck did MvcApplication come from, you might remember MvcApplication was the class that was defined in the
Codebehind file for Global.asax. So it's essentially the class that represents this application. This class will be compiled into an
assembly, which is the OdeToFood.Web assembly, and it is this assembly that contains MvcApplication that I want Autofac to
use. I just need to reference that type and then ask for the assembly property on that type. And now it's my opportunity to also tell
the ContainerBuilder about the specific services I have. So I can say dear builder, I want you to register a type. So in other words, I
want you to use a specific type, which is the InMemoryRestaurantData class, and I'll need to use Ctrl+period to bring in
thatnamespace. So remember, that's in the other project, it's an OdeToFood.Data .Services. I want you to know about this type, and
in fact, I want you to use this type whenever someone asks for an object that implements IRestaurantData. So this is the syntax in
Autofac to say, please register this type, InMemoryRestaurantData, Autofac now knows about that type, and use that type
when someone needs something that implementsIRestaurantData. And hopefully you can see where this is going. If you haven't
worked with a container or haven't worked with dependency injection before, anywhere in my application I can now ask
for IRestaurantData, and I can receive whatever type is specified here, and later in the future if I ever want to change away from
using InMemoryRestaurantData, I only need to make that change once here inside of ContainerConfig. And furthermore, I can
specify a lifetime or an instance of InMemoryRestaurantData. In other words, there are additional methods here available through
Autofac to tell it that I want to create an instance per HTTP request. In other words, any time you receive a new request, I want a
newinstance of my InMemoryRestaurantData. What we probably want to start with is a single instance, or a singleton, because I'm
going to have all my restaurant data inside of the same object, and when I start adding restaurants and editing restaurants, I want to
have a consistent data source. So I'm just going to specify a single instance. Of course this could never, ever, ever work if we have
multiple users because those multiple users will beediting the same source of restaurant data. That's something that a
relational database is designed to do, and that's something we will have later in this course. But for right now, to keep things simple,
we will use InMemoryRestaurantData and we will use it as a singleton. Now, I just need to create my container from
this ContainerBuilder. So if I go to the builder object and tell it to build the container, I now have something that I cangive to the
MVC 5 framework to tell the framework whenever you need to resolve dependencies, please use this container. And I can do that
by going to a class known as the DependencyResolver, and this is a class that is defined by the MVC 5 framework. So I need to go
toDependencyResolver. IntelliSense jumped in and was a little bit eager there. But if I hit Ctrl+period, DependencyResolver is
in the System.Web .Mvc namespace. It is a class with a couple static members. One of these members is a method
called SetResolver, and I need to pass in my Autofac container as the resolver for this entire application, and I can do that by using a
wrapper provided by the Autofac library, which is theAutofacDependencyResolver wrapper. Use that to wrap a container for
consumption by the MVC 5 framework. So just to summarize what we have done here, we are constructing an Autofac container
by registering all of our controllers, as well as our InMemoryRestaurantData component, so whenever something needs
an IRestaurantData, this container should be able to handle that scenario, and then we've set our container as the
dependency resolver throughout the running of this MVC 5 application. So anywhere the MVC 5 uses dependency resolution to
injectdependencies, our container can jump into action. Let's do a build on the application and come back to the browser where
previously we had an error because the MVC 5 framework didn't know how to construct a home controller any longer. But now
with Autofac doing dependencyinjection and my Inversion of Control container, Autofac can look at the constructor for the
controller and say, I know all about IRestaurantData, you told me what to use, so let me pass in a new instance of that object, the
service that you told me to construct, and our application is again up and running.

Understanding MVC Controllers


Applying the MVC Design Pattern
Hi. This is Scott, and in this module we are going to dig into the C of the MVC framework where C stands for controller. The MVC
design pattern has been around for a long time, and it is a design pattern that encourages a separation of concerns, meaning that we
don't want to write codethat tries to handle too many problems in one block of code. We want to separate the concerns or separate
the responsibilities. Perhaps you've also heard of the design principle, the Single Responsibility Principle. The Single
Responsibility Principle is a principle you can apply at the class, function or component level, and it is a principle that the MVC
design pattern encourages. Because when an HTTP request arrives at our application, there's many different things that we need to
do. We need to log the request. We need to query a data source. We need to produceHTML. There's a lot going on. But here's how
we apply the MVC pattern to this problem, the MVC pattern that the ASP.NET MVC framework is named after. First, let's imagine
a user or a client or some computer sends our application a request, an HTTP GET request to the URL/restaurants. So I am
assuming you know a little bit about the HTTP protocol, and you'll recognize that a GET request is a request to read some
information from the application. So someone wants to read about all the restaurants that we have. And with the MVC framework,
the firstcomponent or the first piece of code that we write that can receive that request will be a controller. So it is a controller that
responds to an external stimulus. And one of the things we'll have to do in our application is configure what's known as routing that
will route a given request to a specific URL into the code that we write, into the C# code that we write inside one of our controllers.
So assuming that GET/restaurants, assumingthat request ends up inside of a controller, let's call it the restaurant controller, it is then
that controller's responsibility to respond to that requestwith what the user wants. So, if the user wants to see a list of all the
restaurants that we know about, the controller doesn't immediately render the HTML that our user wants to see. Instead, the
controller is going to build what we call a model. That's the M in the MVC design pattern. Wetypically want to think of the model
as encapsulating everything that the user needs to see on this particular URL. So if I come to your application and I go
to /restaurants and I want to see a list of all the restaurants, perhaps I want to also see a count of the total number of restaurants, and
let's say restaurants broken down by cuisine type, just a count of how many restaurants serve French, how many restaurants serve
Italian and Indian, and so forth. If that's the case, the model, in addition to containing all the restaurant information that needs to
be displayed, can also contain the summary statistics that need to display on that page. But the model itself, again, does not render
or produce the HTML that is going to go to the client and display in their browser. Instead, the controller, after it builds this model,
is going to select a view. I'll often use the phrase the controller is going to render a view. So a controller gets to pick a view, and the
view's only responsibility in life is to produce HTML. So the view takes the model that the controller has put together that contains
all the information that needs to appear in that HTML, and the view only is responsible then for producing the HTML and placing
the data into the right places in the markup that is being emitted. In other words, the view would never do data access directly. The
view would never directly call a web service to get restaurant information. All of that work is taken care of previously inside of the
controller or inside of a service that the controller calls. The controller is simply trying to build a model that will respond to a GET
request for /restaurants. The controller can then select a view and say here's the model that you need to present, and the view will
render the HTML back to the client browser. This is what the MVC design pattern is all about, and this is what ASP.NET MVC is
designed to do. Let's look at a simple example next.

Working with Query Strings


So far in this course, we have built an application that will display a list of restaurants on the home page. This is a list of restaurants
that we maintain in memory. We haven't placed them into the databases yet. And we also respond to /Home/About, as well as
/Home/Contact, and we added one additional endpoint here, which was /greeting. And you might remember that came from a
controller, which was the GreetingController. And this is where we saw the essence of the MVC design pattern. The
GreetingController receives a request for /greeting, itbuilds a model, which is our GreetingViewModel. It can do that by putting
information together from a database or other web services, or in thiscase from the configuration for the application. And then
this GreetingController says let's go out and render a view. Since we are rendering a view from the index action of
the GreetingController, the MVC framework will go looking for an Index view that is a file named Index.cshtml in the
Greeting folder of the Views folder. And indeed, that is the sequence of events that will produce this web page that says have a great
day! By the end of this module, what I want to do is have the ability to go to /restaurants and see a list of my restaurants that include
links to navigate to the details for a specific restaurant, sort of a master details view. So have a master view of all the restaurants
and have a detailed view of individualrestaurants. And before we do that, let me just remind you that the reason we can get to this
controller when we go to /greeting in the application is because the routing information that has been configured in Route.Config .cs
in the App_Start folder. So this single default route says take anincoming URL that is /something/something/ perhaps something
else and treat the first segment of that URL as the name of a controller. So /greeting would tell the MVC framework to go looking
for a controller named Greeting. And then there is no action specified when I have just/greeting, so the default action would
be Index. But I could go to /greeting/sayhello, but that would not find this Index method. It would, however,find this method if I
named that method SayHello, but we will leave this as Index. But what about other information that might be in the URL? For
example, what about anything that might be in a query string? The query string is a very effective tool when we're doing
web programming. The query string effectively allows us to pass a piece of state along in the request. For example, I could have a
query string here and I could sayname=Scott, and now when the MVC framework goes to the GreetingController it still executes the
Index method because the query string does not influence the selection of the controller or the action. But let's say this is a piece
of information that I want to retrieve. It's not an Id because I'm not saying /greeting/index/ some ID. It's simply a query string
parameter named Name. But one way I could access that piece of information is to go to a property that is available inside of every
controller known as the HttpContext property. And one of the members of HttpContext is the Request property. This Request
property will tell you anything and everything that you need to know about the current request. So if I wanted to, for example, look
into the collection of query string values I could say tell me if there is a value for the query string name. This would be one way to
access that information. But I just want to tell you, when you're working with the MVC framework you generally do not need to
access the HttpContext property directly. Instead, what I can do is simply say that this method takes a parameter of type string, and
we'll give that parameterthe name of name. And now the MVC framework is going to try to do everything it can to populate this
parameter when it invokes the Index method. So the MVC framework is going to go out and look around inside of the request to see
if it can find anything with the name of name. And one of the places the MVC framework will look is in the query string. So it will
find a name value in the query string. And if I rebuild this project justto make sure everything compiles, and now let's pass this
name along to our view. So inside of the GreetingViewModel, in addition to passing a message which we get from a configuration
file, let's also add a property named Name. And then inside the GreetingController we are going to say that model.Name equals the
incoming name value, or let's see what happens if Name arrives as null. We'll use the Null-Collation operator to use the string no
name. Let's save that file and come over into the view and let's add Model.Name here to the end of the message. Let me save all
files and do a build. Let's come back out to the browser and do a refresh. I'm going to refresh /greeting query string name equals
Scott and I can see, Have a great day, Scott! But if I change the name to Alex, I can also say, have a great day, Alex! And as we
work our way through the course we're going to find many instances where behavior like this is helpful. For example, when we
need the user to create a new restaurant and they need to give us a restaurant name and a cuisine type and all that information,
how are we going to put that information together inside of an MVC controller? We're simply going to tell the MVC framework
about the pieces of information that we need and the MVC framework will be able to go out and find those pieces of information.
Now what happens if I do not pass a name? In that case you'll notice I get the value no name, and that simply means the MVC
framework did not find a value for name anywhere in the request, so it passed in a null value for that parameter. And the last bit I
want to show here before we move on is that if I try to do something sinister, which you always have to be careful about when
you'reechoing user input back into the page. So for example, if I try to create a script tag here and try to pop up a JavaScript alert
that says hello, that particular request is going to be rejected because ASP.NET has some built-in protections. So if it sees an
incoming HTTP request that contains markup in something like the query string, the request is just going to be rejected. There's a
way to disable that feature of ASP.NET, but in general it could be very dangerous to receive markup from the user, particularly if
you're going to echo that input back onto the page. That is how cross-site scripting attacks happen. The other protection I have from
cross-site scripting attacks in addition to this feature, which will flat out reject the request, is the feature that Razor views will do
HTML encoding by default. So even if my application would accept that incoming markup, my Razor view would display that
markup as inert text when I rendered Model.Name. So that's just a quick security tip for you. You can try it yourself. You can try
putting HTML markup in the message and see what Razor renders. There is a way to force Razor to render the raw HTML, but
we'll talk about that later in the course. For right now, I want to talk about two types of controllers that are available with the MVC
framework.

Understanding MVC and API Controllers


We know that the C in the MVC design pattern stands for controller. And in the design pattern there's really only one type of
controller. A controller is always a component that responds to some external stimulus like an HTTP request and the controller
builds a model and uses someview to render that model. In ASP.NET, I want to tell you that there's really two different types of
controllers. Both of these controller types are still just controllers when it comes to the MVC design pattern, but when it comes to
MVC the framework, the specific implementation provided by ASP.NET, there are some subtle differences between these two
different types of controllers. The first type of controller is the controller like we see here with the GreetingController.
This controller derives from a controller base class that is in the System.Web .MVC namespace. This type of controller is designed
to respond to an HTTP request by building a model and returning a view to render that model. This type of controller is really
optimized for building web applications. These are applications that primarily render HTML to a browser. So a user interacts with
this application by using a browser, by filling out forms and clicking buttons in the browser window. All that results in HTTP
messages that are sent here to my server and handled by a controller. They're handled by a controller which builds a model. It can
do that by talking to an in-memory datasource or to a SQL database or to a document database, talking to a configuration file, but
ultimately it builds that model and then selects a Razorview to render that model and send HTML back to the client, to the browser.
The other type of controller is what we call the Web API controller. The API controller, as the name implies, is designed and
optimized for building APIs. So instead of using a browser, if my customers and my clients, they're all writing software in C# or
JavaScript or some language and sending me HTTP messages programmatically, and all I want to do isrespond using JSON or
XML or some standard data format like that, that is the scenario that Web API controllers are optimized for. So the controller
in System.Web .MVC, that's best to use when you're building HTML. The other controller, the Web API controller, is best to use
when you want to build something that consumes JSON or XML or produces JSON or XML. So when I go to see a list of all the
restaurants in this application, if I want to take that model, the list of restaurants, and produce HTML the best class for me to use is
the System.Web .MVC controller. On the otherhand, if I want to take my model and instead render or produce JSON or XML, then
I should use the Web API. So we will talk more about the Web API later in this course, but most of this module and most of this
course is going to be using the System.Web .MVC controller. I do, however, want to provide a little demo so you can see what an
API Controller looks like. So to do that I'm going to right-click on my project and I'm going to say that I want to Add a New Folder,
and I'm going to give this folder the name API. This is not required, but I've decided that I'm going to keep my API controllers in an
API folder and my regular controllers, the System.Web .MVC derived controllers, keep them in a Controllers folder. So neitherof
those folders are technically required, but this a pattern that you'll see in many MVC projects. And now to add a Web API controller
there's several different approaches that I could use to do this. I could right-click and say that I want to Add a New Item, and under
New Item I couldselect that I want a Controller or that I want a Web API Controller. But I'm going to go to New Scaffolded Item.
I'm going to make this selection, and it's from here where you can clearly see there is the concept of an MVC 5 Controller, and
that is the System.Web .MVC type of controller. So something that is typically used for producing HTML, and then there's also
the Web API Controller. Technically Web API version 2. This is what I want to add. I'm going to click the Add button and I
will have to give this controller a name. Let's just go ahead and give this controller the name of RestaurantsController. So
you're going to see many similarities between MVC controllers and API controllers. They have some of the same naming
conventions. So I'll give this controller a name that ends with the word controller and I'm going to click Add. And I'm going to make
sure that I do this under the API folder. So let me just go ahead and say add New Scaffolded Item, Web API 2 Controller, and I'm
going to say RestaurantsController. Let's go ahead and click Add. Visual Studio will now run some scaffolding and make a
few changes to my project. It will add a RestaurantsController.cs file to my API folder. I expected that. It also added
a README.txt file that I can view here, and I can see that the scaffolding has added a full set of dependencies for ASP.NET
Web API 2. So I have all the references and NuGet packages that I might potentiallyneed inside of this project. But as
the README states, there may be some additional changes that are required to enable this Web API 2 to work. So there's some
configuration that has to take place for Web API to work. What I need to do ultimately is look inside of Global.asax .cs, make sure
it has these two namespace references. Let me copy those. Make sure it has an Application_Start method, and make sure that I have
a piece of code that will call into a method that will configure the Web API to work appropriately. So let's go ahead and scroll down
here to Global.asax. Here's the Global.asax .cs Codebehind file and I'm going to open that up. I'm going to paste in those two using
statements that I copied from the README file. Then I can see that I already have System.Web .Routing included, that's good, so I
don't need to add that line. But I have added ausing statement for System.Web .Http, and then going back to the README file I
also need to make sure that this method is inside of the Application_Start method. So the Application_Start method is in this file. It
already exists. And what I want to do is paste in this line of code thatsays GlobalConfiguration.Configure, WebApiConfig.Register.
I'll tell you what this does in just a second, but I just want to point out for right now to make sure that you place this line of
code above the line of code that says RouteConfig.RegisterRoutes. You might remember we talked about RouteConfig a little bit
earlier. RouteConfig, if we open that up, tells the MVC framework what rules to apply to map an incoming URL to a specific
controller. We've already seen that /greeting will go and look for something called the GreetingController. Now let's open up the
method that isspecified here, which is WebApiConfig.Register. Once again, this is trying to ultimately invoke a method that will
configure the framework to behave the way I need it. And in this case this register method is a static method on a class,
WebApiConfig, that is in this file that has been added to my App_Start folder. So again, everything inside of here, code that I need
to execute during startup to configure the framework and theapplication to behave the way I need, and this part of the configuration
is dedicated to the Web API. Now, I'm going to toggle back and forth between RouteConfig and WebApiConfig because you'll
notice there are very similar settings here. Both of these configuration methods essentially tell a framework to say take a URL like
this and map the first part to a controller name. And then take an action name and then an ID. Sosomething like greeting/index
would go to the Index action or the Index method on the GreetingController. WebApiConfig.cs, very similar, but notice this starts
off with the literal text, api, which just means that the URLs that I need to reach my API controllers are going to start with api. So in
order to reach the RestaurantsController that we just scaffolded into the project, I would need to go to /api/restaurants to reach
that particular controller. Let me copy that string because what I want to do is go ahead and do a build in Visual Studio just to make
sure everything works andeverything is up to date. It looks like the build has worked, and now let me do a Ctrl+F5 to run this
application in a browser. And I want to take that URL that I just copied and paste it up here. So I want to go to /api/restaurants and
I'm going to see an error message. But it's not just any error message, it's an error message in XML. Because in a way, the Web API
framework knows that I'm sort of trying to reach this RestaurantsController, but there's really no action, there is no method on
this controller that matches this request. And instead of just displaying a typical HTML-based error page, it's going to return an error
message, but in XML format. Let's see if we can add something to that RestaurantsController which Ialmost got to through
/api/restaurants by adding some code to that controller. So let's open up the controller, the RestaurantsController, so I can see
that the routing rules are very similar, but one difference between API controllers, which you can see is the base class here, and
HTML controllers or MVC controllers, is that with MVC the method that I want to reach is typically in the URL. In other words,
/greeting/index would say go to the Index action on the GreetingController. With Web API, there is no action specified in this
string. Instead the action that you're going to choose is typically based on the HTTP method that is used. So HTTP methods include
GET, PUT, POST, and DELETE. Those are the four common verbs that we have. And if I write a piece of JavaScript that is going
to do an HTTP POST to a certain controller or certain URL like /api/restaurants, the Web API will say, oh, this is an incoming
POST message, let me look for an action or a method named POST. So in a browser, if I just send off a request to /api/restaurants,
that is an HTTP GET request, so the HTTP method being used is GET. And that means inside of thiscontroller if I create an action
named GET, I should be able to respond to this incoming request. Let me just write a simple method that returns the string, Hello,
World. I will do a build to this project. Let's come back to the browser and let's do a refresh, and I can see that my API controller,
the surrounding Web API framework has taken the model that I've built, which in this case is just a simple hard coded string, but it
could be a list of restaurants that I query from a database, let's say, it's taken my model and it's serialized it for me into in XML, and
it's doing that by default because of the specific headers that this browser sends. I could also make a request to my web service, to
my Web API, and request the information be in JSON format, in which case I'd get back a JSON string. So now we know just a
little bit about API controllers. So now before we leave this topic of API controllers temporarily, let me just show you an example
of how we could return restaurant information.

Installing and Configuring Web API


To see a little more how an API controller compares to an MVC controller, let's go ahead and work through the scenario where I
want a RestaurantsController to return a list of the restaurants. The list will be in XML or JSON format. And ultimately
this controller's going to end up looking a lot like the HomeController. The HomeController currently on the Index action, which is
the home page of the application, we need access to a database. We tell the database layer to give us all the restaurants, and we're
going to use a View to render those restaurants inside of a table or inside of a list. We need to do something similar with our API-
based RestaurantsController, including getting access to the data source. So, once again I don't want to instantiate some sort
of restaurant data object directly. I want to be able to write a controller and ask the framework to inject and provide for
me something that implements IRestaurantData. We will just call this db. Once again, I'll place my cursor here onIRestaurantData,
hit Ctrl+period. That's in the OdeToFood.Data .Services namespace. So I will select that entry and press Enter. And then I will also
place my cursor over the db parameter and select the option to Create and initialize a field with the same name, db. So doing that
will give me a private read only field where I say what the value that is in that parameter. Now I have access to a data source. So
inside of GET, I can say that my model is what happens when I ask this data access component to give me all the restaurants. And
now, instead of returning a view, which will take that model and present that model in HTML, things are a little bit simpler
because all I want to do really now is return the model. It turns out that the Web API framework can figure out how to serialize this
object. It can figure out the best format for the client that is trying to reach me. But there will be a compiler error because I'm no
longer returning a string. Instead, what I'm returning is an IEnumerable of restaurant. I will also need to bring in the
OdeToFood.Data .Models namespace. Now I have code that compiles, but is not necessarily going to run. Let me go ahead and do a
build on the project. Let's come back to the browser, and now instead of displaying Hello, World, I will receive another
error message in XML. An error occurred while trying to create a controller of type RestaurantsController. Make sure that
the controller has a parameterless publicconstructor. We went through this exercise before. Unfortunately, the MVC framework and
the Web API framework, they are two separate frameworks that get rolled up inside of ASP.NET MVC. But since they are two
separate frameworks they have different configuration systems anddifferent approaches to resolving dependencies. So you might
remember previously in the course, we came into your Global.asax .cs file and we created a container, an Inversion of
Control container that is using Autofac behind the scenes. And we plugged that container into the MVC framework by setting
a DependencyResolver. So DependencyResolver, the SetResolver method is a static method on this class DependencyResolver.
And you'll notice in the pop-up window that DependencyResolver is in the System.Web .MVC namespace. So this is
theDependencyResolver for the MVC framework. I also need a DependencyResolver, the one that is associated with the Web
API framework. So the easiest way to do this is going to be to reuse this RegisterContainer method and have this method register a
container for both the MVC framework and the Web API framework. And what I will do is pass in the Web API configuration that
this RegisterContainer method needs to modify. So that particular configuration, the Web API configuration, is in a class
System.Web .Http .GlobalConfiguration, so System.Web .Http, the primary namespace for everything Web API. And what I want
to do is walk up to that class, and it has a static property that is available, which is Configuration. So now I will be passing in an
instance, an HttpConfiguration object. So back in ContainerConfig.cs, let's take an HttpConfiguration object and I will name that
parameter using the name HttpConfiguration. I do need to bring in the namespace, which is, again, System.Web .Http that lets me
know I'm dealing with the Web API. And this HttpConfiguration will have a property available, which is DependencyResolver. So
you might be wondering why these two frameworks are so different, Web API and MVC, they just evolved differently. So
ASP.NET MVC uses a static method on a class called a DependencyResolver. The Web API with this approach of having an
instance of HttpConfiguration where you have aproperty on that configuration object which represents the
DependencyResolver. But this is what I need to set. And now, instead of sending it to an AutofacDependencyResolver that wraps
a container, I need to set this to an instance. So I'll still use the new key word of anAutofacWebApiDependencyResolver. Now
this class does not exist in this project, that's why I have a red squiggly here. And unfortunately, it exists in yet another NuGet
package that we do not have installed. But if I place my cursor there and press Ctrl+period, Visual Studio is smart enough to say,
oh, I know about this particular type, it's in a NuGet package that I know about, a NuGet package Autofac.WebAPI2. So if I scroll
down and select that option, I could also tell Visual Studio to go ahead and find and install the latest version. And Visual Studio will
go out and find that package and download it and it is now available for me. And that's the same thing that would have happened if I
would have right-clicked on the project and said Manage NuGet packages and gone out and found that and installed that
package myself. Ultimately in both cases, thatpackage will be listed here inside of packages.config. And yes, there's Autofac.Mvc5
that we installed manually earlier, and here's Autofac.WebApi2 that Visual Studio just installed for me. So now, unfortunately, we
have to go through all this configuration for that little bit of code inside of our controller to work. But now that this is in place it will
work for all future Web API controllers that we placed into the project. There's just one more thing that we have to do. When
we built this container, we had registered in this container all of the regular MVC controllers that are in this application. But we also
need to register our API controllers that are in this application. So I'm going to copy this line of code and I'm going to paste it, but
change the method call so that in addition to registering regular MVC controllers, we also register API controllers. So just a little bit
of setup has been required here. I'm going to press Ctrl+B to build, and I obviously missed a semicolon down here on the bottom
line. So let's tryCtrl+B, Ctrl+Shift+B to build again. I have a project that is built successfully. Now what I should be able to do is
refresh /api/restaurants and, yes, I am now dealing with an array of restaurants and I can see the three restaurants that are in my data
source. This is in XML because the particular headers that my browser, Firefox, sends to the web server will indicate to the Web
API that the preferred format here is XML. But I could alsoexplicitly ask for JSON. In fact, if I switch over to the console real
quick, and I'll just do this as a quick demonstration, I have the WindowsSubsystem for Linux installed inside of Windows. So I can
use the cURL utility to send off a quick web request. What I'm going to do is copy this URL and say that I want to send off a cURL
request to /api/restaurants, and you can see in this case where I don't explicitly send any headers that indicate the type of data I want,
I get back an array of objects in JSON format instead of XML. Now with cURL I have a little more control overexplicitly what is
going to happen here because I can specify my Accept header. So I can say I want to Accept application/json, and my response will
be in JSON. Or I could say I want to Accept application/xml to receive my response in XML. So the Web API has a feature known
as content negotiation that tries to figure out what does the client want? Do they want JSON? Do they want XML? And it
can modify the serialization accordingly. But for now, let's leave the API controllers for later in the course and just focus
on building HTML applications with our MVC controllers.

Building a Restaurant API


Now that we have an API endpoint for restaurant information, let's create a dedicated section in the application to not only show
restaurants but also, ultimately, edit, create, and delete restaurants. Currently all we have is on the home page, I'm showing a list of
the three restaurants that we pull out of the in-memory database we've come up with. But I want a dedicated section. So I want to be
able to see restaurants here in the menu. And I want to be able to click on that entry to go to a list of restaurants and I want to be able
to drill into specific details about a restaurant, as well as create and edit and delete restaurant information. To manage all those
features, I'm thinking about another RestaurantsController. But this time not an API controller for restaurants, but a regular MVC
controller for restaurants. So this controller that I'm about to build, it will still be namedRestaurantsController, but hopefully by now
you'll be able to see that when I go to /api/restaurants I'm looking for an API controller with this new controller we're about to build
by going to /restaurants/index or /restaurants/detail I want to go to a regular MVC controller. So, once again, let's get some help
by scaffolding out this feature. I'm going to right-click on the Controllers folder and I want to Add a New Scaffolded Item. And let's
start off with an MVC 5 Controller that starts off just empty. And we will call this a RestaurantsController. By default, what I will
have scaffolded here is a controller that has an Index action that returns the default view for this particular action. So remember,
over in the Views folder, I will now have a folder dedicated to the views for this controller, so that's the Restaurants folder, and it's
inside of here where I will be able to ultimately find views like index.cshtml. You'll notice that file does not appear inside of this
folder, that's because we didn't scaffold a controller with a view, we just scaffolded an empty controller. And really one of the
easiest ways to scaffold this controller is to right-click inside of this method and say that I want to add a view. The tooling in Visual
Studio is pretty smart, it will come up and say, yes, the view name is Index. But right now let's just scaffoldout an empty index to
make sure we can get this to work. And inside of this Index let's just say, hello. If I do a build in the project, Shift+Ctrl+B, it should
come as no surprise that if I go to localhost port whatever and go to restaurants, so not /api/restaurants, but just restaurants, I indeed
see that view that I just created that says, hello! But how can I come to this URL without typing in the address bar? In other words, I
want another entry up here that will allow me to just click on a name for restaurants and be able to come to that URL. Well,
we talked about this a little bit earlier in the course. We talked about the layout view that ASP.NET MVC uses and this menu is part
of the layout view that I want to modify. So I want every page in my application to be able to have a link up here that will take me
to the list of restaurants and we can then remove that feature here from the home page. So first, let me come into the Index view for
the home page. I just want to go ahead and remove the display of restaurants that we have. We could still tell everyone how many
restaurants are in the database, we're just not going to list the restaurants on the home page. But I do want to be able to navigate to
the RestaurantsController. So inside of the Shared folder is where I can find the _Layout file. It's inside of here where we will find
the navigation menu for the entire application. It's right here where I can find the links that I can click on to go to the Index action of
the HomeController or the About method of the HomeController or the Contact method of the HomeController. What I need is
just one more entry inside of here. So one more call to the HTML helper known as ActionLink. And what will ActionLink
do? ActionLink will take the parameters and the information I'm giving it and figure out what is a link, what is the URL that I can
formulate inside of an anchor tag. So it's trying to build an anchor tag with an href attribute. What is the link that I can place in the
href attribute that will lead to this action on this controller? Sofirst of all for a controller name, I want the RestaurantsController, and
I'm going to copy that bit of text because it turns out that's the text I want to display to the user. I also want to display restaurants
there. And then what is the name of the action that I want to reach on that controller? The name of the action that I want to reach is
the Index action. So behind the scenes, ActionLink will take these pieces of information and it will goconsult the configuration that
the MVC framework has and says if I want to reach the Index action of the RestaurantsController, what URL should Iuse? And
that's what will be placed into the href attribute for the anchor tag that gets created here. Let's go ahead and do a Shift+Ctrl+B to
build the project and come back to the browser. I want to refresh, I see those restaurants disappear. I see a new entry for restaurants
up here and,indeed, it does point to /restaurants. Notice that the logic in the MVC framework determined that, oh, since we want to
go to the Index action of the RestaurantsController and since the Index action is the default action for every controller, then all I
need to do is specify a URL of /restaurants that will take you there. So now I can start to navigate through these different features of
the application. And with that in place, let's next build out our list of all available restaurants.

Scaffolding a Restaurant List


If we want this view to show a list of restaurants, then back in our controller code inside of the RestaurantsController we should
build a model that includes a list of all the restaurants that we want to display. So let's go ahead and add a constructor. I want
something that implements IRestaurantData, we'll call it db. Press Ctrl+period to bring in the namespace, OdeToFood.Data
.Services. Press Ctrl+period again to create and initialize a field named db using this incoming parameter. And now I can build a
model. And I can say that my model will be what happens when I invoke the GetAll method and I can now pass this model along to
the view to render a table. So very simple logic inside of my controller action. And now, let me delete the existing index view that is
inside of the Restaurants folder. I'm going to delete that view because we're going to recreate that view to display a list of restaurants
instead of just saying hello. So again, right-click inside of the controller action. I'm going to say that I want to add a view. Again, it
will be the Index view, but instead of a template being the Empty template, notice these different template types that are available.
And I know if I'm working with a list of something, whether it's a list of employees or a list of albums or a list of restaurants, any
time I have a list I can select the List template to scaffold out most of the HTML that I would need to display that list. All this
dialog needs to know is what is my model class. So I'm going to type in restaurant, and that is correct, it's the
OdeToFood.Data .Models .Restaurant. I'll leave all these other settings in place. We'll talk about things like partial views later in
the course. But right now I'm just going toclick Add, and what should come out is an Index view that already has an
@model directive that says the model type for this particular view is going to be an IEnumerable of Restaurant. So it's going to be a
collection of restaurants. It's also going to execute a little bit of code to set the Title property of ViewBag. We're going to come back
and talk about that a little bit later in the course. And it's going to have an ActionLink to a method or an action on
my RestaurantsController that doesn't exist yet, but we'll create it in the next module. And that will be a link that will allow me to
create a brand-new restaurant. And then everything after that is really about setting up a table to display information about all the
restaurants thatI have. So here's the opening piece of my HTML table. Notice we'll have a row with some headers inside. This first
header will say basically this is the column to display the restaurant name. And then, just like we had when we were displaying a list
of restaurants, an unordered list, we're going to set up a foreach loop, but now instead of displaying list items, we're going to set up
table rows with table cells inside. And we're beingintroduced to some new HTML helpers here, DisplayNameFor and DisplayFor.
So once again, these are HTML helpers that are just trying to make it easy to create HTML based on metadata and information that
is available in your application and on the objects that you're using. So when I usedHtml.DisplayNameFor, this particular method is
just trying to put together some text that it should show the user, so what to display for this particular property name. That's a little
bit confusing because the property name is Name, but what I'm saying is give me the name that I should display for this
particular property, whatever it is. And that's written as a lambda expression here. Now I will show you later in the course how
youcan add specific attributes and metadata to your application to influence how these HTML helpers behave. And that can be
very useful because you can write a single model class and use that to drive certain features in your user interface like what text is
displayed, what validation rules are applied, is a null value or an empty value legal in this particular property or not? We'll see all
that later in the course. And then down here inside of the table, in the right most table cell there will be a collection of links that
will allow me to do things like edit a restaurant, go to the details for aspecific restaurant or delete a restaurant. We'll talk about
this additional parameter here in just a bit. And of course, we don't actually have Edit, Details or Delete as methods or actions inside
of our controller, but we will be adding those features throughout the rest of the course. But right now I just want to see if this is
working by doing a quick build that will make sure that all my files are saved. I'm going to come back out and refresh the browser
when it's sitting on the /Restaurants URL. So again, that should render the Index action of the RestaurantsController, and there I can
see in a nice format the list of all my restaurants and I have the ability to interact with those. If I tried to go to one of these actions,
like show me the details for that particular restaurant, I will have 404 Not Found error. And that's the MVC framework saying
essentially, sorry, but I couldn't find a Details action on the RestaurantsController. We'll be filling all that information out.
But notice one thing that doesn't appear here is the cuisine type. And, of course, if you're building something that is your own model
or you're using restaurants but you're adding more properties to your restaurants, of course you can have as many columns here as
you want displaying as much information as you want about a restaurant. But we're going to rely on the details view to provide most
of the details that we want to see about a restaurant. Let's implement that next.

Scaffolding Restaurant Details


Inside the application, let's try to go to the details for Scott's Pizza. Notice the link that I'm clicking on down in the lower left of the
browser window in the status bar. You can see I'm about to go to /restaurants/details/1 because Scott's Pizza is the restaurant with an
ID of 1. But when I navigate to that URL I receive a 404 Not Found error. Let's hit the Back button and then try to fix that
particular problem. So inside of theRestaurantsController, the MVC version of the RestaurantsController, what I need is a public
action, so a method that returns ActionResult named Details. Now to display the details of a particular restaurant, I'm going to need
the identifier of that restaurant. And the good news is that ID is included in the URL. So when I go to /Restaurants/details/1, that
value 1 in the third segment is going to be the ID that I need. And as we saw earlier in this module, if I ask for an id parameter
to this action, the MVC framework will do everything it can to find something by the name of id. So it is going to look in the query
string, but it's also going to look in the data that was extracted from the route. So, of course, in RouteConfig thatthird segment of the
URL is a piece of information that I told the MVC framework to identify as an id. So that becomes a parameter. And over here
in RestaurantsController I should be able to receive that id just by asking for the value here inside of the controller action. I expect it
to be an integer, but in reality that ID could be anything, it could be a string, for example. Let's treat that as an ID. And my model
should be the restaurant that has that identifier. Currently the only thing we can do with IRestaurantData is get all of the restaurants.
So I'm going to need a new method that will allow me to query for a single restaurant by id. Let's go over into the Services that are
available in OdeToFood.Data because I want to change IRestaurantData. In addition to a GetAll method, I want a method that will
return a single restaurant. And let's just call it Get. You pass in an id and I expect this method to return just a single restaurant that it
finds by that id. Now we will need to implement that method in ourInMemoryRestaurantData source. And if I place my cursor here
on the interface that I want to implement, IRestaurantData, Visual Studio has detected that I have not completed the implementation
of that interface because I am missing this GET method. But if I press Ctrl+period, I canimplement the interface again and
Visual Studio will generate that method for me. This will throw a NotImplementedException, but let's remove that and
return restaurants. And let's use the link operator FirstOrDefault. So what I'm going to say is given a restaurant, r, give me the first
restaurant where the id property matches this incoming id, or if you cannot find a single restaurant like that, just return the default
value for therestaurant type. Restaurant is a reference type, so the default value would be a null. So here I will either get back
a reference to a restaurant or I will get back a null reference. And coming back to the RestaurantsController, if I save all my files, I
should now be able to say db.Get and pass in the id. That is going to be my model, and ultimately what I want to do is return a view
that consumes that model. Currently that view does not exist because by default that will look in the Restaurants folder of the Views
folder and it will look for a view named Details.cshtml. That does not exist. But once again, I can right-click on this method, say
that I want to add a view, and, yes, I do want the view name to be Details. Now the template that I want to select will be the Details
template. This particular template assumes you're going to pass in a model that will be a singleobject of the following type. And
I'm going to type in Restaurant. So it's going to be a single restaurant, and what the scaffolding engine in Visual Studio will do is
analyze that particular model and generate a view that will display all the properties and all the values for that restaurant. So let's
click Add, and I now have a view that is strongly typed to take a model type of Restaurant. It's going to display in an h2 tag that this
is a Details view. Let's go ahead and add @ Model.Name here. So we can say Details for, and provide the restaurant name.
And another way to do that is to use Html.DisplayFor. What's the difference between the two? Well, Html.DisplayFor will use
additional metadata to format the name. So if I just say Details for and then @ Model.Name, I'll always just be showing the model
name, but there's data annotations and data attributes that I'll show you later in this course that you can attach to the model to
influence the behavior of DisplayFor. And I can say things like if the name is a null value,instead display this string. And I can also
do some fancy formatting. So when it comes to properties that are of type decimal or double or float, I can say to display this
particular value using so many digits after the decimal point. I can format dates so they display without the time portion of the date
or times without the date portion and so forth. And you'll notice I basically have a view that is using dl and dt elements to display
just the restaurant name. But remember, we also have a restaurant cuisine. And you might be wondering why that's not showing
up. And it's just that the scaffolding engine with Visual Studio doesn't take to enum types that well. So it's just not going to display
them by default. But it's going to be easy enough to add. Let me copy the dt and the dd cell and say that I want a DisplayNameFor
the Cuisine and I want to display the value for Cuisine. So DisplayNameFor is displaying the name for this property, and what is the
name for this property? It's going to come out as Cuisine and this is displaying the value for that particular property. So again,
it would be easy enough for me to hard code here just Cuisine, and it would be easy enough for me to say just @
Model.Cuisine here. But sometimes using these HTML helpers is beneficial because you can drive different behaviors and
different displays in your application just by attaching different pieces of metadata to the model. And I promise we'll see that later in
the course. For right now, let me save all the files and do a build. We should now be able to respond appropriately when I click on
the details for Scott's Pizza. And indeed, I do now arrive at the detail view that will show me the name of the restaurant in
the header, as well as the name of therestaurant here and the cuisine here. So, we're dealing with a very small model. It really only
has two properties of any significance, plus an ID property. But obviously you can build this view to handle as complex a model as
you need. So if you have a department model that has a collection of employees and every employee has a collection of addresses,
you can use a series of loops to display all that information on the details page. There's nothing in the MVC design pattern or
the MVC framework that will limit your abilities. So notice this details view when I scaffolded this view, it also provides a link to
edit a restaurant, we're not quite there yet. We'll look at that in the next module. I also have a link to go back to the list. So back
to the list of all restaurants and I can go to any restaurant now. But what happens if instead of going to /Restaurants/Details/3, which
is a restaurant that exists, what happens if I try to go to a restaurant identifier that does not exist? Now I have a bit of a problem
because the application is unhappy. It's thrown an exception. I can see inside of one of my Razor views I now have an exception,
Object reference not set to an instance of an object. And this probably is not the behavior that I want to have in my application. So
let's see if we can make this a little bit better in the next clip.

Working with Action Results


We can see the details of the exception that we're getting a null reference exception when we're trying to create a link to edit a
restaurant and using the expression Model.Id. Obviously model is null when we try to reach a restaurant that doesn't exist and we
allowed our data layer with that link FirstOrDefault operator to return a null value when it doesn't find a given restaurant. So
one way to solve this problem would be to modify our view to not make assumptions that there will always be a model. So I could
place a statement in this view, something like if Model equals null, andthen branch and display different HTML when model is null.
But in general I try to avoid that type of logic inside of a view. That type of logic really is better handled at the controller level,
because the controller should be able to look at the model and say, oh, I tried to query for a specific restaurant and we didn't find
that restaurant. If we didn't find that restaurant, why am I trying to render the view that displays all the details for a specific
restaurant? I should do something else, have some different behavior instead. And that's where we can discover there's actually a
number of different helper methods on a controller that allows us to return different types of action results. So I could say if
the model is null, then I want to special case this and I want to do something other than returning the default view, which is
the Details view. What I could do is return an HTTP status code to the browser that will tell the browser to please
redirect somewhere else. So what I could do is say, no, please redirect this request and go back to the Index action on the
same controller. And yes, I can also use RedirectToAction to redirect to an action on a different controller if I wanted to. I could
also return a view, and one of the parameters to this view method is the View name. So if I pass in a string as the first parameter to
the View method, that is not using that string as a model, instead what I'm saying is go out and find a view named NotFound. And
so remember the controller does get to select which view will render. In this case, I can say return the view that says, sorry,
we didn't find that restaurant versus the view that actually displays the details for a restaurant. All I need to do in this situation now
is add a view, add a view called NotFound. I will use an Empty view. Let's go ahead and click Add and let's just change the display
around. We can say Sorry, That restaurant is not found. I'm going to save this file. I'm also going to come over into the Details view
and I'm going to copy this line of code that generates a link that goes back to the list of all restaurants. So let's place that here to
make it easy to navigate back to the entire list. Let's do a build on the project and let's come out to the browser. And now if I
refresh, /Restaurants/Details/11 instead of receiving an error page, I receive a page that says Sorry, That restaurant is not found.
Now I can click to go back to the list of all restaurants. And that's a much nicer user experience than what we had before where
there's an error on the screen. And now, let me just give you a little bit of a tip that will give you some more information about
routing inASP.NET MVC. At the beginning of this module I already showed you how with ASP.NET MVC I can pass and
receive parameters in the query string. And I can receive a value that's in the query string inside of a controller action and use
that value. Knowing that, let me just show you what happens if I come in and I change my routing configuration a little bit.
What I'm going to do is instead of saying that I have an id in this position, I'm going to say that I have something named key. So the
key for the restaurant that I want to see. And just to make this example complete, let's just say that key is also an optional value. So
the MVC framework doesn't need to see this in a URL, it is optional, but when someone wants to pass me a key it's going to appear
in the URL. Let me just show you a difference in the application now if I do a build and I do a refresh on my list of restaurants then
I come in to go to the details for Mango Grove, I just want to point out that the id is now passed in a query string. So again, the
HTML helper that we are using to generate that link the, HTML helper that says please generate a link for the details action on
theRestaurantsController, and by the way, pass along something named id with the value of 3, now that particular HTML helper
when it consults the routing configuration, it does not see a way to pass the id in the URL, because the RouteConfig now only has
controller and action and key. But that doesn't stop us from generating a link because I can also pass information in the query string.
So I can say query string ID equals 3, and thatwill bring me to the appropriate restaurant. I can even say /Restaurants/Details/5
query string ID equals 3 and still end up on the same restaurant because that key value, the value 5 that the MVC framework I told
it was a key value, that's available to the controller, we just don't use it. But nowtypically something that really identifies a resource,
like this id value, it really identifies a specific restaurant that is in my system. I really want that to be part of the URL, part of the
path of the URL, not just a query string that is almost sort of an optional parameter that modifies an existing query through
a resource. I really do want that to be part of the URL. So I'm going to come back into RouteConfig and press Ctrl+Z to undo
mychanges, make sure that anytime someone wants to pass an id, they can appear in the URL. So let's do a build. Let's come back
to the list of all restaurants, and now when I go to the details for Mango Grove, I can see my ID is back in the URL. But anytime
when you're trying to work with something that you want to appear in a URL segment or you're using an ActionLink HTML helper
and that ActionLink is placing something unexpectedly into a query string, now you know that what the software is doing is trying
to work with the routing rules that are configured in your application to make sure the information is passed along
appropriately. And if it's appearing in the query string, that means the software didn't find a way to place that particular value into
the URL. And so at this point we've built in a few more features to our application. We now have the ability to display restaurants.
We have a dedicated restaurants link so the user can come see the restaurants. We're showing the details for our restaurant. And in
the next module, we can build on this information to start understanding how we can create and edit our models. So how can I
create new restaurants and save them in the database? And how can I edit an existing restaurant and create a form that allows the
user to fill out information about the restaurant and save that to my data source. That's what we'll be looking at in the next module.
Using MVC Models
Understanding Models and View Models
Hi. This is Scott, and in this module we're going to look at using models and view models. So far in this course, we have seen that
when a user opens a browser and sends an HTTP request to our application that the MVC framework is going to use routing rules to
try to route that request to a specific controller. That controller's then going to build a model, and then that controller is going to
select a view to render that model. It's going to pass the model along and the view is going to produce HTML. So what's the
difference between a model and a view model? Well, a view model is a concept that I like to talk about. A view model is a model or
a class that you have built whose only purpose, whose only responsibility is to encapsulate and carry all the information that is
needed to render a view. In other words, some of the models that might exist in our applicationserve dual purposes. Let me give you
an example by flipping over into our application. Let's go over into the OdeToFood.Data project and let's pull up the Restaurant
model. So yes, we can say that Restaurant is a model. It's a relatively simple model, but it's a model nonetheless, but many people
would actually call this Restaurant class an entity. Restaurant is an entity because it represents the information that's going to be
persisted into a database. And later in this course we're going to be using a framework called the Entity Framework to store and
retrieve restaurant information into a SQL Server database. So Restaurant is a model. I could also consider it an entity, but it's
definitely a model and I can use it as a model because we've already seen in the RestaurantsController when someone is trying to
find the details for a specific restaurant. The exact model that I build and pass over to a view is a single restaurant. But what I want
to make you aware of is the fact that entities don't always make the best models for a view because quite often a view will
need more information than you can have from a single entity, like Restaurant. And inthose situations, quite often, I like to build
what's known as a view model whose only responsibility is to provide all the information and behavior that is needed for one
specific view. So a good example of that would be the GreetingViewModel. This is not information that I persist in the database.
This is all the information that I need for a specific view that the user's trying to see when they reach the GreetingController. And
there's nothing that says I couldn't do something like include a property, which would include a list of the restaurants that I know
about. So let's create a property named Restaurants. All I need to do is make sure I spell Restaurant correctly and bring in the
namespace, OdeToFood.Data .Models. And I now have a view model designed for my greeting page that can not only display the
current message of the day, but also contain a collection of entities, which are the restaurants that I know about in my database.
Other pieces of information that a view model can carry along to a view might include lookup data. So let's say that we're going to
edit a restaurant. When I go to edit a specific restaurant, like Mango Grove, I need more information for that particular view than
just the data that is stored in the database. I need more information than just the name of the restaurant and the cuisine type. I need,
for example, a list of all the available cuisines that a user can select from when they're editing that restaurant. We'll see that exact
scenario in this module. And now that I've had the opportunity to tell you about the philosophical differences between a model and a
view model, let's jump into a scenario where we're going to edit some restaurant data.

Setting up a Create View


Currently in the application if we go to localhost/Restaurants we'll end up on a list of all the restaurants that we know about. This is
what we implemented in the last module, and we did that by scaffolding out this view, and the scaffolding included a link to create
a new restaurant. This goes to /Restaurants/Create, but currently results in a 404 not found error because we have no action in our
controller that can respond to an action name of Create. So let's add one. Back in Visual Studio I'm already inside of
Restaurants.Controller .cs. So let's create a new action thatreturns an ActionResult, going to be named Create. I don't need to take
any parameters in this case. I don't need an ID because I'm going to create a restaurant out of thin air, or more precisely out of the
information that a user gives to me, which means I don't even need to do any sort of data query either. Let's just see what happens if
we just return a view that can create a restaurant. Once again, I'm going to use the Visual Studio scaffolding to create that view. So I
can right-click inside of the method and say that I want to Add View. The view name is going to be Create. The template, in this
case, I'm going to select the Create template, and the model class, once again, will be Restaurant. And here again I want to point out
that if I have a view model, that is a class whose sole purpose is to carry along all the information that I need to create a restaurant.
Really, the way to think about it in an edit scenario is this view model encapsulates all the information that needs to be exchanged
during a particularoperation, so not necessarily presented, because another use of a view model is to receive inputs from a user. So I
can have a view model whose only responsibility is to receive the information that a user is going to type into a form. Because
once again, quite often, that information can be different than the information that I store in the database, which could
be represented by an entity. In this case we're going to use this Restaurant class. So something that I use to carry along the data that I
need to show when I display the details for a restaurant, as well as an input model, so something that I will use to collect information
from the user before I store it in the database. So it's operating both as an input and an outputmodel. But I still wouldn't
necessarily consider Restaurant a view model because that's not its only purpose in life. It's also an entity. And with thatclarification,
let me go ahead and click Add to scaffold out a create view. And now just to test this out, let me do a build inside of my project and
come back to the web browser. I want to refresh /Restaurants/Create, and I do have now a response that displays this view
that allows me to enter a restaurant name and then click on a Create button to save that restaurant. So once again we're in a situation
where the scaffolding didn'tquite properly handle the enum property that we have on a restaurant, the cuisine type, which isn't a big
problem. We can go in and add that by hand here in just a moment. But I do want to point out something a little more subtle that
is presenting this create view. This action obviously isn't creating a restaurant. This action is responding to an HTTP GET request.
And a GET request, by the way, will never or should never perform a writeoperation on my server. And essentially what this action
is doing is responding to a request to get a form that will allow a user to create a restaurant. That's the way to think of this. I'm not
actually creating a restaurant in this action. I'm giving you the HTML that you need to create that restaurant. When the user actually
clicks on this Create button, expecting to save that restaurant into the database, that's going to be a different,another action that we
have to create that will receive the restaurant information and then validate that information and save it in the database. We're not
quite there yet. First let's come back to the view that was created, the Razor view, the cshtml file, and inside of here you'll see a few
more HTML helpers. Again, all HTML helpers are just here to help you emit snippets of HTML. So what does Html.BeginForm
do? Html.BeginForm will render a form tag. By default, the method on this form will be a POST method, and by default the action
on this form, which tells the browser where to post to, is going to be the same URL as where the form came from. So if this form is
being delivered from a URL /Restaurants/Create, the default action when I click on a Submit button inside of the form is to post
back to /Restaurants/Create. That's what BeginForm is doing. There's also this little trick that is taking advantage of the C# using
statement to close the form when we hit the bottom of this code block. So down here, by wrapping that in a using statement, when I
close that using statement, close that block, that will essentially emit the /form closing form tag. So that's all the begin form is doing.
AntiForgeryToken is going to emit a hidden input into this form. We'll take a look at it in the browser in just amoment. But the
value of this hidden input will be some cryptologicly significant value that ASP.NET can use to ensure that the form the user is
submitting is a form that came from your site and not some other malicious site that is trying to trick the user into submitting a form
to your site. So, an AntiForgeryToken, if you want to do more research on why this exists, is here to help us prevent cross-site
request forgeries. So I'm notgoing to go into a lot of detail about cross-site request forgeries, but I do just want you to remember that
anytime you're in a situation where you have users filling out forms, you should use AntiForgeryTokens, especially if
your application requires authentication and you use cookies, or authentication ticket cookies, to authenticate your users. In those
scenarios it is especially important to use an AntiForgeryToken. Now many ofthese other HTML helpers, as we're going to see, emit
little bits of HTML and help us implement everything that we need for this form. For example, what happens if there are validation
errors on our model? Currently we're not going to have any validation problems with our model because we're not performing any
validation, but when we do later in this module, we'll see how HTML helpers that revolve around validation, like
ValidationMessageFor, can automatically display validation messages for us. And those messages can be styled using Bootstrap
styles to call out that something is an error or something is dangerous. So this @class syntax is a way to set a class attribute on a
particular HTML element. So let's say that ValidationMessageFor ultimately renders a span that says something like This name
is required. That can be a validation error message that appears, but we want to style the text inside of the span to make sure it
stands out. We essentially want to add a class of text-danger, which is a class that is included using the Bootstrap CSS framework.
Again, not a topic I'll get into a lot in this course, but you can find plenty of courses on Bootstrap at Pluralsight. But my overall
point here is that the syntax for doing that is the syntax you have here. Essentially with many of these HTML helpers you can
pass along an anonymously typed object, and the Razor View Engine will take the properties on that anonymously typed object and
write those properties out as HTML attributes, and then whatever value you have for that property will become the value of
theattribute. The reason the at sign is here is because in C# it is not legal to have a property name of just class. Class is a keyword,
but the C# language also defines that if you use the at sign, that's sort of like escaping that keyword. So yes, you can have a property
named @class, and theRazor View Engine is smart enough to recognize that, oh, you want to write out a class attribute with this
value. So that's what's happening here. Sometimes that parameter is explicitly specified as the htmlAttributes parameter. So
that's what's happening here with EditorFor. What does EditorFor do? EditorFor, again, like all these other HTML helpers, will look
at metadata about this particular property to try to figure out what is the best input to place into this form. So if you don't know
anything about HTML form and how form and inputs and input type equals submit work, you might want to go through a bit of a
refresher before you start down this path using Razor views and HTML helpers. It will certainly give you a better idea of what's
happening behind the scenes. But EditorFor will essentially create an input, so in this case an input that the user can type into, and
the type of this input could vary. So in this case, what the HTML helper EditorFor will do is look at name, see that it is a string
property,and so the best type for this input is probably going to be the text type. Later in this module I'll show you some of the data
annotations that you can attach to a model so that EditorFor can see things like, oh, this is actually going to store a password. So
maybe I should make the type password, or I will make the type password instead of text. But these are all things that the HTML
helpers are doing. They are emitting all the markup that we need to not only edit specific pieces of a restaurant, but also to
show labels for the user and to show validation messages when something goes wrong, which is good, but before we can have a
complete form that allows me to create a restaurant, I'm going to need to dosomething that will allow me to edit the cuisine or
specify the cuisine type of a restaurant.

Working with Enums


Let's add an input to our form that will allow a user to specify the cuisine for a restaurant before they create the restaurant. So back
in our create view, which I do want to point out takes a model of type Restaurant, we have all these HTML helpers like EditorFor
that allow us to specify a property on that model type and then just provide the right type of editor or provide the right type of
display for a label that displays for that property. I want to do the same thing for the cuisine property, but the cuisine property's
a little bit different just because it isn't enum. Wat I'm going to do, though, is copy this form group because basically every piece of
information that the user needs to edit is going to follow this generalpattern where I want a label and an editor inside of a form
group, and I also want any potential validation messages that are associated with that particular property inside of that form group.
So I'm going to copy this form group and then we're just going to change things around so thatinstead of being a form group for the
name of the restaurant we're going to change these things around so this is for the cuisine of the restaurant. So this is going to write
out an HTML label. The label for helper will look at the metadata for this Cuisine property to determine what is the text that I
should display to the user when they input this field. And yes, once again, we have some htmlAttributes that will add classes
of control-label and col-md-2, both Bootstrap classes. This will add these class specifications to the HTML that is emitted. Then we
have a div with a specific width that first of all has an EditorFor. In this case I want to change this to Cuisine. And then if there are
any validation problems, I also want to display any validation messages that are associated with the Cuisine. Let me save that Razor
view file, the .cshtml file, and do a refresh out here. And what I now have is a textual input for the name of the restaurant, as well as
for the cuisine of the restaurant. But this might not be quite what I want because this is essentially a free form text entry. And if I'm
only expecting certain values for the cuisine type, then I really want to restrict the user to only being allowed to select one of the
existing cuisine types that I know about. We'll talk about that in a second, but right now this is free form text. How can I be sure
about that? Because if I right-click on this input and say that I want to inspect this element, I will see that I have an input whose
type equals text. So I can type anything into this input. I also just want to point out up here at the top, this is the form that was
emitted by html.BeginForm. So notice the action is /Restaurants/Create because we came from /Restaurants/Create. If you want this
form to post or to get to a different action, that is a different controller action, there are parameters that you can pass to
html.BeginForm so that when the user clicks the Submit button or this form is otherwise submitted, it will go to a
different controller action. But for right now by default, this is going to post back to the RestaurantsController to a create action, a
new create action that we're going to have to add to the RestaurantsController. I'll show you how to do that in the next clip, but I do
just want to point out the RequestVerificationToken that is here. Again, that is here to help prevent a cross-site request forgery,
which is something you always want to do. Let's see if there's something different that we can do for Cuisine so that the user
justdoesn't type in whatever they want for the cuisine type. And it turns out there is a different HTML helper that I can use when I
have a property of type enum. So first of all there's lots of different HTML helpers inside of here. There's HTML helpers for
validation messages, to create different types of inputs, to create a list box or a list of items, to explicitly create password inputs, and
there is also one for creating a drop-down list based on an enum type, so EnumDropDownListFor. And by switching from
EditorFor to EnumDropDownListFor, I should have a different display inside of my view. So now instead of saying I want some
sort of editor for this particular property, I'm being a little more explicit and I'm saying I want a drop-down list, which behind the
scenes is really an HTML select element. A select element with options that are built out of the values for thisenum. So in most
cases, you just want to use EditorFor when you want to provide an input for the user, but there are some special circumstances
where you have to be a little more explicit, and in this case I have to be explicit and say I don't want just any editor, I specifically
want a drop-down list. So if I do a refresh, I have essentially an HTML select. If we inspect this element we'll see it's a select. And if
I expand this we'll see the options are all taken from the definition of my enum and the values will match the matching enum entry.
So Italian is 1, Indian is 2, French is 3. And although this drop-down list could probably do with a little bit of styling, a user can
now safely select just one of the cuisines that I already expect. And now I could fill out a restaurant name and I could click Create,
and what's going to happen next? Well, currently in the application nothing is going to happen because currently in the application
that form will send a request to /Restaurants/Create. We'll end up at this existing Create action, but all this Create action will do is
re-render the view that the user can use to fill out this information. We're not actually going to save anything. We're going to need
a different action for that. Let's talk about that in the next clip.

Implementing the Create Action


What I'm about to show you is going to be a common pattern that you'll see when you're programming with the MVC
framework, and that pattern is this. Any time you're implementing a feature or a scenario where the user needs to edit data, you
typically have a pair of controller actions that are required to implement that feature. The first controller action will be the controller
action that gives the user the form that they fill out to edit or create a particular resource. And the second controller action will be
the action that receives the information that the user has filled out. So in other words, I'm going to need a pair of Create actions,
one action that simply returns the view, which contains the form that the user can typeinto, and another action that receives
the restaurant information back from the user. So this particular action can take a parameter of type Restaurant. I do need to bring in
the namespace OdeToFood.Data.Models. I can give this parameter the name restaurant. And what we're going to see with the MVC
framework, just like we've seen before, any time I have a parameter on an action method, the MVC framework's going to do
everything in its power to try to populate that parameter for me. So we saw this when we implemented the Details action and I
asked the MVC framework to provide me with an id. The MVC framework could find the id in the routing data from the URL. We
also saw that earlier when we were toying with the GreetingsController and I passed a name in the query string. So the MVC
framework was also able to find a name parameter to pass into an action method from the URL. This restaurant is going to be a little
bit different, but the MVC framework is still smart enough to say, oh, you need an object of type Restaurant, and I see that a
restaurant has an id property and a name property, and a cuisine property. Let me go looking for something with those
names anywhere inside of this request. And you have to remember the browser behavior, when I have a form like this and I fill out
this information and I click on the Create button, the browser is going to collect things like the inputs and the selects that are in this
form and submit them to the server, and it's going to submit the values using the names that I specify for these selects and
these inputs. In other words, if I have a select whose name is cuisine and whose value that the user selects is a 1 or a 2 or 3, then that
is going to be one of the values that the browser submits to the application back to the server when it posts to /Restaurants/create. So
the MVC framework is going to be smart enough to say, oh, I see someone is posting a form value with the name of cuisine, and I
see someone is posting a form value with the name of name. This input type equals text, so let me go ahead and create a Restaurant
object for you and just push those values into this restaurant. This is a process known as model binding in the MVC
framework. With the values that I expect to receive from a user, and the MVC framework willautomatically populate this object
with values the user is entering in a form. We'll see how that works in just a second. Now, anytime I have a POST operation, I want
to make sure that I validate that anti-forgery token that is included in the form, especially, again, if I'm using authenticated users
with cookies. I always went to validate that anti-forgery token, and I can do that here on the server side just by placing an attribute
on mycontroller action. So I will validate the anti-forgery token, I will receive the user input into this Restaurant object that the
MVC framework will create for me using model binding, and now all I need to do is save that restaurant into my data source. We
currently don't have a feature that will allow me to save a restaurant, so let's go into our interface, or IRestaurantData. I'm going to
create a very simple method named Add that will take a restaurant parameter, and I expect anyone who implements this interface
then to save that restaurant. So let's go to our InMemoryRestaurantData source. I'm just going to paste that method definition here,
add a public access modifier, and now how do I add a restaurant to an in-memory data source? Well, let me just simply walk up to
our list of restaurants and use the Add method to say, I want to add this restaurant into the list. That'sreally all I need to do for
in-memory data. But a couple things here. So, first of all, remember, this just is a list of restaurants in memory. Anytime
myapplication resets or re-cycles, or if I close Visual Studio and come back tomorrow, any new restaurants that I've added to this
list will be gone. They will have disappeared. We will fix that problem later when we actually hook up something that talks to SQL
Server. But just be aware that while you're testing this application, you might do a build with some new code, and all of a sudden
you are missing some restaurants that you've typed in. That's just going to happen with the in-memory data service. One other thing
to keep in mind is that when we start using SQL Server, we're going to be using SQL Server to generate IDs for our restaurants. So
SQL Server has a feature where anytime I insert a new record into atable, SQL Server can generate a unique identifier for that
particular record. We're going to rely on that feature to generate IDs for our restaurants. Our in-memory data, this list, has no
such feature, but we still need these IDs in our application so that we can navigate to specific restaurants. So I need to generate an
ID for this new restaurant that we're adding, and I'm just going to use some simple logic that will only work in this scenario where
I'm running an in-memory list of restaurants, and I'm doing that in development where there are no concurrent users. So obviously
thiswould never work in production. None of this would ever work, not if I have real users and simultaneous users. But for right
now, I'm just going to say that this restaurant's id property is going to be equal to, and let's go out and find the existing largest id in
our collection. So if I say restaurants.Max, so it's the LINQ Max operator, given a restaurant R, let's look at the id property. Tell me
what the maximum value is that you see and then just add 1. That will be the id for the new restaurant that is being added. And now
I have a method that I can invoke to add a restaurant to my data source. So let's just do that here inside of Create. I'm going to do the
simplest possible thing that could work right now, which is just to walk up to my data source, say that I want to add a restaurant, and
we're just going to leave everything in place. I'm going to do a Build, and I'm going to come back to the browser, and we're about to
find out that this doesn't quite work just yet, but I want to show you what happens. For the name of the restaurant, I'm just going to
enter in Scott's Place because that's different than Scott Pizza, but set the cuisine type to Indian. Let'sclick create, and what I'm going
to find is that the MVC framework isn't quite happy yet. So yes, the MVC framework can see that I want to go to
the RestaurantsController, it can see that I want to find an action on that controller named Create, but it sees two possible candidates
for that action. So it sees these to create methods, and it's giving me an error saying it doesn't know which one to select. Well, you
know and I know that I expect this version of Create to be invoked when I click on that Create button in the form because I'm
posting back to the server, and that post includes restaurant information. But the MVC framework's not going to make that
guess, and it's just going to throw an exception. I need to be a little bit more explicit and say this particular version of Create should
only respond to an HttpPost. So that's the big difference between these two action methods. This Create method should only
respond to an HttpGet request, because this is the action where I want to get the resource that will allow me to edit a restaurant, edit,
or create, or type in the information. This version of Create is where I'm writing or I'm posting those values to save them into
the database. And really, only the HttpPost attribute is required, because that would be enough to differentiate between this first
Create action and this Create action. But a lot of people like to add these attributes everywhere so that it's very explicit that actions
like Detailsonly respond to a GET request, and actions like Index, they will only respond to a GET request. And that's a reasonable
thing to do. And now, if I do a Build, we should have something that's a little more functional. So let me go into the address bar and
press Enter. This should send off a GET request to /Restaurants/create. So let's try filling out this form again. I'm going to fill out
Scott's Place. I'm going to select a cuisine of Indian, clickCreate, and what happens? Well, currently, our controller is simply
returning the Create view when I post information to the server. That's not an ideal thing to do for many reasons, and I need to come
up with a better user experience. We'll get there, but there are a couple things we need to work through before we come up with a
better user experience. And for right now I just want you to see that, yes, we're saying render of the Create view, so that's what we're
seeing on this page. If I come to the list of restaurants, I can see Scott's Place actually was successfully added. But we did add this
place without performing any validation on the model. So let's talk about some validations next.

Validating Models and Model State


One of the problems with our new create a restaurant feature is that we perform no validation. So if I leave the name empty and
click Create, we have now created a restaurant that has no name. Every restaurant should have a name, so we want to prevent that
scenario. So back inside of Visual Studio, let's think about how to add some validation features. We want to have some validation
features that will work with our view so that when there is a problem with the name or there's a problem with the cuisine, or there's
just some sort of general problem with the model, any validation or error messages that we have will work with these HTML
helpers like ValidationMessageFor and ValidationSummary. And the way to make that work is to work with a data structure that is
available inside of a controller known as ModelState. So ModelState is a property that you inherit in your controller, and anytime
that you have model binding happening, like when you take a parameter of type Restaurant, or even when you take a simple
parameter of type int, like an ID, ModelState is going to contain information about what happened during that model binding. So if I
go into ModelState, you'll notice it's a collection because really it's a ModelStateDictionary. What I'm looking at as a data structure
that contains all the byproducts of what happened during model binding. And I can go in and I can ask for specifically what
happened when you tried to bind the name property to the restaurant. What is the underlying value that the user tried to enter? And
what errors are associated with that specificfield? And the HTML helpers in our Create view are going to use this information
in ModelState when they display that form. Not only to show validation errors, so messages that would appear in this
errors collection, but also when displaying the value that is inside the input for thisassociated property, like Name. Because imagine
I had a property that only allows integer values. So I want the user to enter the year the restaurant was created, for example. But the
user enters the text xyz and tries to place that into the integer property for the year. Well obviously my model cannot accept
that value. It cannot take an xyz when it expects an integer, but the ModelState can represent the attempted value that the user tried
to put in of xyz. And so when I display this form back to the user to display the information that they entered along with the
associated error so they can now fix those values, I can display that value xyz for the year property of a restaurant. So these are
some of the things that ModelState will do for you. I can also explicitly tell ModelState about errors. So let's check if
restaurant.Name, let's check if it's null or empty. So if String.IsNullOrEmpty restaurant.Name, then I know I have a validation error.
So what I'm going to do is walk up to ModelState and say that I want to add a new model error. The key that I use to add this model
error will be for simple models just the name of a property that has the error.So in this case I'm just going to use a nameof
expression and say nameof restaurant.Name, and specify an error message, The name is required. And then I can continue adding
more validation checks here inside of my controller action, and ultimately what I want to do is I only want to add this restaurant to
my data source if ModelState doesn't have any errors. And I can check for that by asking ModelState if everything is valid.
SoIsValid only returns true if there are no model errors. So only if the ModelState is valid will we add the restaurant to the data
source. Otherwise, what do we do? Well in this case let's return that Create view because we want to present or re-present the Create
view that the user is trying to enter this information into, present that form now with all the errors that are associated with the values
they entered, and allow them to fix thisproblem. This other return view that we have here, we're going to change that in just a bit.
I'm going to leave it here for now because all I really want to show you is that now if I do a Build in this application and I come out
to the browser and I say I want to create a new restaurant, and then I just immediately click Create without entering a
restaurant name, I can now see the error message that says, The name is required. So this is oneapproach to validation. I check my
model values inside of my controller action. If I find any problems I can add those validation errors into ModelState, and then when
the Create form displays or redisplays because I have returned that view, the HTML helpers like EditorFor
andValidationMessageFor could look at ModelState to say oh, I found a ValidationMessageFor the name. I'm going to display that
message inside of a span. And I wanted to show you this approach to validation because this is really what's happening behind the
scenes, but of course it would become tedious to go through my application and in every place where I might be editing restaurant
data, I have to add these sorts of rules. Now this is one way to do validation, it's a low-level attempt at validation, but I do want
you to note that the MVC framework provides some features to make validation a little bit easier than this. So some
validation checks are so pervasive that they exist everywhere. So making sure that somethingisn't empty, making sure that numbers
are in a specific range, and if those are the types of validation checks that I'm making, there's an easier way to do that. Let me show
you the approach next.

Validating Models with Data Annotations


Although what I'm showing you here is something you can do for validations, if all your validations are simple and common like
required fields and ranges, there is a better approach to validation. So I'm going to remove this validation logic check from inside of
my controller action, and instead introduce you to data annotations. Data annotations are pieces of metadata that you can attach to
your models and your view models that caninfluence model validation during model binding, as well as how the HTML
helpers present your information. So let's open up our Restaurant model and come to the name, and I want to use a data annotation
named Required on this name. So if I press Ctrl+period, I can add a reference to the assembly that contains this
particular annotation, and that is the System.ComponentModel .DataAnnotations .dll. I'm going to add that, and that is also going to
add a using statement for SystemComponentModel.DataAnnotations. And now anytime the MVC model binder runs validation
logic across my model, if I'm using Restaurant as an input model to an action, the MVC model binder will see this data annotation
and will inspect the Name property to make sure the Name property is not null or empty, and if it is, the model binder will
automatically set an error into ModelState to mark ModelState as invalid. So that logic I had in here before with the if statement
is essentially taken care of for me by the default model binder in MVC. There's many other data annotations that you can add, and
you can add them all inside of one pair of square brackets, or you can place them on separate lines inside of other square brackets.
With some of the other annotations, you'll see in that namespace include RegularExpression. So I can specify that the value of this
property has to match this RegularExpression that I'm specifying in the data annotation.There is also, for number values, a
Range attribute, so I can say that something has to be between the value of 1 and 10, for example. And there's also data
annotations that influence the display of a particular property or property value. A good example would be DisplayFormat. In this
case I'm not adding a data annotation that drives validation logic in the MVC framework, I'm adding an annotation that adds
that metadata that I've been talking about that things like HTML helpers can use. So notice with DisplayFormat I can specify
a DataFormatString. So if I have a propertythat is an integer or a property that is of type datetime and I want to format the value
when it displays in the browser in a particular way, I can set a DataFormatString here. This uses all the regular formatting strings
that you can find in .NET. I can also specify a null display text. So if something is null, like the restaurant name, but I don't want to
try to display a null or empty value in my view, I could use NullDisplayText to change that. There's also DataType. The DataType
annotation is useful when you want to specify something that might be just a plain type of string actuallycontains HTML or an
ImageUrl or a Password because when you use something like Html.EditorFor to say I want an editor for this particular field, if the
MVC framework sees that that field is really of data type Password, it can render an input, type equals password. So when the user
types into that input, we don't see the characters that they're typing, we see that masking character the browser has used. Like the
little dot that appears foreach character when you're typing a password. There's also a display attribute. So I can say that the name
of this particular property, when you'redisplaying a label, is not just the name of the property. That's what the MVC framework uses
by default, Cuisine, but I could come up with something different like Type of food. And if I do a Build, let's come back to our
application and let's just go back to the list of all restaurants. Let's come into the Create New form freshly, and you'll notice
now instead of displaying Cuisine it displays Type of food. And the nice thing about these data annotations then is that it doesn't
matter where I'm binding against a restaurant, I'm always going to have this validation to make sure that the restaurant name is in
place. And I'm always going to have this metadata that says don't just use the property named Cuisine, display the text Type of
food. That's really the power of data annotations, to centralize that logic and centralize that metadata and use it to drive all these
other features inside of the MCV framework.

Following the POST-Redirect-GET Pattern


Now we have our validation logic in place, but there's still a problem with this form. It might not be obvious at first. But let's create
another restaurant. And I will even name the restaurant Another Restaurant. We can set the Type of food to Italian, click Create, and
again, the create action re-renders the Create form, which doesn't really make sense for the user experience because to the user,
to me, it looks like I have not completed this form as yet. So we have to do something different. And there's also a potential problem
here. If I'm on this page now and I click Refresh in the browser, well, every browser knows that it just completed an HttpPost
action. So an HttpPost rendered this form. And everybrowser knows that refreshing a post or resending that post operation can
create problems. I could be resubmitting a credit card order. So I could end up with a duplicate transaction. And because of that,
Firefox is trying to tell me, I'm going to send information and repeat that action. Are you really sure that you want to do this? Do
you want to resend this form? I'm going to cancel out of resending this information. And this is a userexperience that we don't want
to place our users into. We want to adopt a pattern known as the Post/Redirect/Get pattern. Post/Redirect/Get says that when you do
an HttpPost for a user like this, when they're posting a form and you've successfully processed that form, you don't want to display
HTML that is a result of that post operation. Instead, you want to send a redirect instruction to the browser, tell it to redirect
to another resource, and go and get that other resource. That way when the user successfully submits a restaurant, and I save that
information in the database, I'll send their browser over to another resource that they get. An as long as that is a GET request, they
can refresh that page or bookmark that page or send as many requests as they'd like to that particular page and not have to worry
about duplicate transactions. So that's the pattern that we want to follow here. When I click Create and I successfully save
this restaurant, I then want to redirect and get a different resource that can show the user that they have successfully saved that
restaurant. That's another important piece of the user experience too. Let'sjump over into Visual Studio and see how to achieve that.
So back in the RestaurantsController, inside of the Create action that takes an HttpPost, if the ModelState.IsValid and I have
saved the restaurant into my data source, I no longer want to return the Create view. Instead, I want to return a response that tells the
browser to redirect to some other resource. So what I could do is use the RedirectToAction helper method that produces an action
result that encapsulates an HTTP redirect. And I could say, well, let's redirect to the Index action. That would take the user to the list
of all restaurants. That could be helpful, but what if I went to the details for that specific restaurant that I just added into the
collection. I think thatwould be more interesting. So we add a restaurant to the data source. Now I'm going to send you over to the
page that shows you the details for the restaurant so you can see it lives inside of the data source. But of course, the details
action requires an ID parameter. So this will not be a compiler error, but at runtime the MVC framework won't have a value to
place into the ID parameter, but you'll notice there's additional parameters that I can pass to the RedirectToAction helper method,
and one of those parameters will be routeValues. So anytime you seesomething described as route values, you can use this trick
where you pass an anonymously typed object whose properties and their values represent the information that you want to pass
along in a route somehow. So that information might need to be passed in the query string or it might appear in a segment of the
URL. The MVC framework will figure out where to place it, but it will be passed along. So I want to say, I want to create a new
object with an id property and set the id property value to the id of the restaurant that we just inserted into the data source. So
theMVC framework should be smart enough to say, oh, you want to go to the Details action, and you want to pass along something
called id with this value, be it a 3 or a 4 or a 5, and I can see where id fits into the URL, so let me create a URL and redirect the
browser to /Restaurants/Details/15, or whatever it is that we just created. Let's try this out. I'm going to do a Build and come back
to our browser. And let's start things off fresh by just going and issuing a GET request to /Restaurants/Create and have a fresh new
copy of the form. And now let me create a restaurant whose name is Another Restaurant part 2. We'll set the Type of food to be
French. I'm going to click Create, and now I am on the Details for that restaurant. So I got redirected to /Restaurants/Details/4. And
now I'm pretty confident as a user that I have saved that restaurant. But even if I'm not, if I click Refresh, I don't have any
warnings popping up in the browser that I need to resend information, and that might cause a problem. I don't have to worry about
that. I can refresh this page. I can bookmark this page. Everything appears to be working. I can also go to the list of all the
restaurants. I can see that restaurant appears here even though we've lost the other restaurants because, again, it's an in-memory list,
and my application got reset when I rebuilt the project. We'll fix that in the next module. But for now, let's take a look at the edit
scenario.

Implementing the Edit Action


After everything you've seen, I think you might be able to implement the edit scenario on your own. I think you should try it now.
I'm going to show you my solution, but I think it would be a good idea to try it on your own. Even if you don't complete
implementing the edit feature, it will give you some great experience to just try implementing this feature. So feel free to pause the
video at this point and come back in when you've finished or you feel like you've gotten stuck and can't make it even further. Here's
what I'm going to do. Over in Visual Studio I'm going to go into myRestaurantsController and really the edit scenario and the create
scenario are very similar. In fact, in a lot of applications, teams will implement editand create using the same pair of actions. We're
going to use some separate actions, but notice that the application is already set up so that if I try to edit another restaurant too, that's
going to go to /Restaurants/Edit/4, so it's depending on an edit action being in place. So first, let's write the action that will return the
form to edit a given restaurant. I will say this action only responds to HttpGet. It's going to be a public method that returns an
ActionResult. Its name is going to be Edit. And Edit is slightly different than Create because in the Edit scenario I need the identifier
for an existing restaurant because I want to display that existing restaurant in a form so the user can change this restaurant. That's
something that's a little bit different. So I need to query for a model, and I can use my data layer to say please go out and get a
restaurant that has this ID. Just like with Details, that could return a null. So I should check if model is null, if so, what would I like
to do? Well, I could return an error, an HttpNotFound error, that would return an HTTP status code 404, or we could do something
like we did in Details, which is if we did not find a specific restaurantwe just returned a special view, the NotFound view. Either one
of those options is reasonable. You just have to figure out what you need for your application and for your users. But if we do find
the restaurant, let's return an edit view that will display that restaurant as the model. Let's go ahead and scaffold that view. So I'm
going to right-click in the method, say that I want to add a view. This view's going to be named Edit. The template is going to be the
Edit template. The model class will be, again, a Restaurant. And I will just click Add to create that view. Like the views we've
scaffolded so far, we will not have the ability to edit the cuisine of a restaurant. So like we did previously for the create feature,
I'm going to copy this form-group that allows me to edit the restaurant name. I'm going to copy that bit of markup and I'm going to
paste it here into the form. And I'm going to modify the markup that I paste so that I can edit the restaurant cuisine. And again, just
like we did in the create scenario, instead of asking for an editor for the cuisine, I'm going to specifically ask for an enum drop-down
list for model.Cuisine. What we're going to discover is that this HTML helper is also smart enough to set the initial selection in this
HTML select to match the current value of the restaurant's cuisine. So this should behave the way you would expect. And so my
view is in place. Let's just do a quick test to see if this part is working so far. I'm going to do a Build in the project, come back to the
application, go back to my list of all restaurants just to make sure that after the data source resets I still have a collection
of restaurants that I can go to edit. And if I go to try to edit Mango Grove I can see I'm on /Restaurants/Edit/3, and I do see the name
of this restaurant and the type of food is correctly selected. So, so far, so good. Now I just need to implement what happens when I
click the Save button and I post this information back to /Restaurants/Edit/3. So inside of the RestaurantsController, let's create
an action that will work for us. So an action that only responds to HttpPost, an action that will validate an anti-forgery token. And
let's create an action that will return an ActionResult. It is named Edit, and as a parameter we will take the restaurant. The first thing
we will check inside of this action is we will check tosee if ModelState is valid. Because if ModelState is not valid, I'm going
to return the current edit view with this restaurant and allow the user to try to fix the model validation errors. I will only do that if
ModelState is not valid. Otherwise, if ModelState is valid I want to save this updated restaurant information, and just like we did
with create, we can then redirect to an action, which is the Details action, and we can pass along the ID of the restaurant. So the
Details action will have all the information necessary to pull that restaurant up for display. But how do we save a restaurant? Well,
we don't have that implemented yet. But with an in-memory data source that should be relatively easy. Let's open up
ourIRestaurantData and add a method that will allow me update our restaurant. So you pass in a restaurant, I will find a restaurant
with the same ID in my list of restaurants, and I will update the data inside. That's at least what we'll do for the
InMemoryRestaurantData. When we're working with a database something different might happen. But let's add a public method
that returns void. Its name is edit. It takes a restaurant parameter, and let's find the existing restaurant. I could do that simply by
going to my GET method, passing along restaurant.Id that will either give me back a restaurant that has the matching ID or it will
give me back a null, so we could say if existing is not equal to null, only then do I want to try to copy some values in
here. Otherwise, we could throw an exception or we could just ignore this operation. We could also return some sort of status
codeor Boolean, or even a restaurant object itself so that the controller knows that something wasn't found that would probably be a
good idea. But let's just go ahead with the logic that we have. I'm just going to say that existing.Name equals the incoming
restaurant.Name, and we will say that the existing.Cuisine equals the incoming restaurant.Cuisine. And of course, we won't try to
change the ID. When we save that file, and with the editoperation in place, let me come back to RestaurantsController and just
say db.edit, or rather db.update, and sorry, we didn't want to call this Edit, we wanted to call this Update. And that should match the
name that I provided in my interface. Yes, update here, also update in the implementation. That will make the compiler happy, and
then over in the controller action itself, we call db.update and we pass in the restaurantthat was put together by the model
binder. And I think the code that we have in place will work. So let me do a Build. We'll come back out to the application. Let's
go to the list of all restaurants. Let's go to edit Scott's Pizza and let's just change the Type of food from Italian to Indian, click Save,
that appears to have been persisted. If I come back to the list of all restaurants and go to the details for Scott's Pizza, it still says
Indian. So it appears my Edit feature works. I should also be able to change the name of the restaurant. So I'll change the
cuisine back to Italian, change the name to Scott's Pizza 2. And all of these changes appear to be persisted in our data source, at least
our in-memory data source. And now what we've seen in this module really represents the bulk of what happens inside of a lot of
MVC applications that I've seen over the years. We have actions that present forms to our customers, our customers fill out
information in those forms, they click a button to post back to our application, we validate the data that they post, and then
ultimately we save that data inside of some sort of data source and display validation errors if there was a problem. We always
validate anti-forgery tokens. And we follow the Post/Redirect/Get pattern. This is all what we've seen in this module, which is a lot
of the day-to-day work that we do with the MVC framework. So now that we have some basic core features in place, let's get the
application working with a real database, a SQL Server database.

Using Entity Framework in MVC Applications


Introducing the Entity Framework
Hi, this is Scott, and in this module we're going to start using the Entity Framework. The Entity Framework is what we call an
object-relational mapper, an ORM. The overarching goal of any ORM, including the Entity Framework, is to make your data easy
to access and manipulate, even ifyour data is living inside of a SQL Server. It should as easy to access as the data that we currently
just hold in an in-memory list. But by placing that data into a SQL Server, into a real database, we'll be able to take advantage of
SQL Server features like transactions and backups and durability. But what we'll discover by the end of this module here as I flip
over into Visual Studio is that querying and updating that data doesn'trequire significantly more code than what we already have
when we're just accessing and updating an in-memory list. In fact, we'll be able to use some of the same LINQ operators, like
FirstOrDefault and OrderBy, against data that is inside of SQL Server and being accessed through the Entity Framework. We'll be
able to use the same LINQ operators that we use against collections in-memory. It's going to be that easy. But before we can get
there, we need to make sure that you do have a SQL Server database installed. In this module, I'm going to be using a version of
SQL Server known as SQL Server LocalDB, but you can use any version of SQL Server that is going to work with the
Entity Framework. The Entity Framework works with most versions of SQL Server, including technologies like SQL Server
Compact edition. Let's first take a look at SQL Server LocalDB.

Working with SQL Server LocalDB


When you install Visual Studio, any version or any addition of Visual Studio, Visual Studio should also install a version of SQL
Server known as LocalDB. LocalDB is a full instance of Microsoft SQL Server that has been optimized and packaged to work best
in a development environment. So LocalDB is not something that you would use for a production website, but it is something that
you would use to develop against and somethingyou would use from Visual Studio. I'm going to be using LocalDB in this
module. Later in this course when we come to deployment, I'm going to show you some deployment tips for deploying
this application into a real web server using a real version or production instance of SQL Server. LocalDB is a real SQL Server,
it's just not a version of SQL Server that I can use for production. You should think of it as your SQL Server that you can use for
development. Now over the years, I've seen many developers struggle trying to connect to SQL Server. So as a first step before we
get started using LocalDB, I just wanted to show you some tips about how to find and verify LocalDB and make sure that you have
it installed on yoursystem. If you don't have LocalDB installed, rerun the Visual Studio installer and make sure you install anything
that is a LocalDB component or aSQL Server component. One way to verify that LocalDB exists is to open up a command prompt.
I'm using the new Windows terminal, but you can open up any command prompt. In order to execute the command I'm about to
show you, you might want to do a search and find the Developer Command Prompt for Visual Studio 2019. This is a shortcut that
Visual Studio 2019 should have created for you. Click to open that command prompt. When it opens up, execute the command
sqllocaldb. Just execute this command and press Enter, and it should return a help screen that describes all the different commands
that you can pass to this utility. What I want to do is pass an i to say I want information about the LocalDB instances that I own, me,
the current user, and tell me about those. I can see there are two, MSSQLLocalDB and ProjectsV13. So I have two instances
of LocalDB executing. These are like two different servers that I could connect to and where I could create databases and store data
like the data about my restaurant. The one I want to use, however, is MSSQLLocalDB. I want to use this first one because the
second one really just used internally by Visual Studio. I can ask for more information about MSSQLLocalDB. I can see that I
am running version 13.1, that my login, scott, is the owner of this instance. It's currently in a stopped state, and that's okay because
we will discover that as long as you have MSSQLLocalDB installed correctly, this database engine can spin itself up on demand. So
when I want to connect to that instance or I need to open a database on that instance, it will start running automatically and there's
nothing I need to do. When I'm done using that instance, it can go away, which is nicebecause that frees up resources for me on this
computer to do other things. That's not a behavior that I would need from a production database because a production database
would be dedicated to running all the time. Now how can I see what is inside of this LocalDB? Well, I could do thatalso using some
command line tools, those command line tools that you can use to connect to SQL Servers and to execute queries against SQL
Server, but I can also use Visual Studio. If I come to the View menu, there is an option here to open up a SQL Server Object
Explorer. So again, thismight be an option that you need to install when you install Visual Studio, but it should be an option even in
the Community Edition. When I click to open up SQL Server Object Explorer, I will see a list of the current SQL Servers that I
am connected to. You'll notice that list is currently empty, so I can right-click on that list and say that I want to add a SQL Server.
Now for this course and for this module, you can use pretty much any SQLServer that you want. You could use a SQL Server that's
deployed inside of Azure, you could use a SQL Server that's somewhere else on your network, you can also use a full instance of
SQL Server that's installed on your machine, like SQL Server Developer Edition. Again, I'm going to show you the steps to use
LocalDB. If I want to connect to LocalDB, I would go to this Local node here under the connection dialog and I would find
MSSQLLocalDB. I can see here that the actual server name is LocalDB inside of parentheses, \MSSQLLocalDB. This server name
is significant because when I tell my ASP.NET application what server to connect to, when I tell the Entity Framework here's the
server you're going to be using, this is the exact syntax that I have to use in the connection string to reach this instance of LocalDB
that I want to use. To make this connection from Visual Studio, I'm not going to be using SQL Server Authentication. That's where
someone gives you a username and a password to log in.I'm going to be using essentially Windows Integrated Authentication. So,
whoever I am, when I'm logged into this computer, those are the credentials that are going to flow through to this particular
SQL Server instance, and I will connect to this instance as this computer name, \scott. Let's go ahead and click on MSSQLLocalDB
and say that I want to connect. I will now have, in my SQL Server Object Explorer, a connection to LocalDB, and I will be able to
expand this tree view here and see a collection of databases that are already attached to this LocalDB. So, you do not need any
of these databases. These are all just databases that I have created over the year just doing some experiments in other Pluralsight
courses. In fact, you'll see there's already an existing OdeToFood database that is here. I'm actually going to delete that database
because that's the database name that I want to use for this course. Let me go ahead and delete that database. Now I should be in the
same state as you, that is, I'm connected to LocalDB, and in my list of databases, there is no database named OdeToFood. That's the
goal, that's what we want to create, and that's where we want to store our restaurant information.

Installing and Configuring the Entity Framework


The first step towards using the Entity Framework is to install the NuGet package that gives us access to the framework itself. We
are going to install this package into two projects, into OdeToFood.Data and into OdeToFood.Web. We're going to use both
projects because most of the APIs and calls and abstractions we're going to be building using the Entity Framework will live
in OdeToFood.Data. But in order for the Entity Framework to execute correctly at runtime, we're also going to make sure that we
have a package referenced to the Entity Framework NuGet package in OdeToFood.Web also because it is the OdeToFood.Web
project that really controls the environment that the Entity Framework is going to execute inside of. The easiest way to install this
package into both projects is to right-click on the solution and say that I want to Manage NuGetPackages for Solution, because in
this dialog, I can go over and browse for packages and install them into multiple projects. Let's browse for EntityFramework. I'm
going to select Entity Framework version 6.2 .0. That is the latest stable version of the Entity Framework. You can feel free to try
the latest version that you see, or if you want to be conservative, go look for version 6.2 .0 to make sure you're using the same
version that I am. You can select the version using this piece of UI. Now with version 6.2 .0 selected, I'm going to select both the
OdeToFood.Data andOdeToFood.Web projects and install the Entity Framework into both of these projects. I will accept the
licensing terms. We'll give this a second to finish installing. We should have now a package reference to the Entity Framework. I
can verify that just by opening up packages.config because in this version of .NET, it is packages.config that keeps track of all the
NuGet packages that I have installed. I can see the Entity Framework is here. There will also be something new in my Web.config
file. If I open up Web.config, it might not be obvious at first, but there's a new configuration section that has been added. This is the
entityFramework configuration section. If I scroll down, I should be able to see that entityFrameworkconfiguration section. I can see
a few things in here. I can see for example that my defaultConnectionFactory, so this is going to be the software component
that behind the scenes sets up a connection or establishes a connection to some data source. The defaultConnectionFactory is going
to be something that uses or assumes we're using LocalDB, which is good because we are using LocalDB. I can also see that there is
a provider configured. A provider is a component or a service that in this case for the Entity Framework provides an abstraction
over a specific data source.So I can see my provider that I'm going to be using in this application with the Entity Framework that's
going to be a SQL Client. So, SQL Client expects to work with some version of Microsoft SQL Server. SQL Client would be
different than other providers that might point to Oracle or SQL Server Compact, or some other database technology that is
supported by the Entity Framework. But as long as you're using Microsoft SQL Server, all of these settings should be fine. There's
nothing you need to change. We just need this configuration in place for the Entity Framework to work. Now with our
NuGet packages installed and our configuration in place, we can now move forward and start using the Entity Framework
baseclasses and APIs to store this restaurant data in a database.

Defining a DbContext
When I'm using the Entity Framework and I want to access data that's inside of a database, ultimately I need to do that through a
class that derives from an Entity Framework base class named DbContext. DbContext with the Entity Framework is my gateway to
any database.Somewhere in this project, I'm going to need to define my own class that derives from DbContext, which tells the
Entity Framework about the types and shape of the data that I want to access. I'm going to place this DbContext-derived class in
the Services folder of OdeToFood.Data.Right-click on that folder and say that I want a new class. I'm going to call this the
OdeToFoodDbContext. That's the name of my class. It will have a .cs extension. I want this class to derive from DbContext and the
Entity Framework. Let's make this a public class. Let's use Ctrl+period to bring in the namespace, System.Data .Entity. That's a
namespace provided by the Entity Framework. So, this is the System.Data .Entity .DbContext base class. And
OdeToFoodDbContext becomes my gateway to a database. I can configure what database I want this to point to despite adding a
connection string to my Web.config file. We'll see how to do that. I can have a single DbContext that points to different databases
when thisapplication gets deployed. When I deploy this application to development here on my machine, I can configure this
DbContext to point to a development database. When I deploy to production, I can use the same class definition with a
different connection string to point this class to adifferent database. Now I'm building a relatively simple project with relatively few
entities. In fact, I have exactly one entity, which is the restaurant. And an entity represents anything that I want to store into the
database. But of course, there's lots of applications out there that need to be built that have to deal with complex databases. So, you
might be on an application that has a database that works with thousands of tables inside. Soyou can use a single DbContext
to encapsulate everything that you need from that database, or many projects I've worked on also break up a database into multiple
DbContexts. So you might have the SalesDbContext, and it will point to the same database as the AccountingDbContext or the
OrdersDbContext. Ultimately, all those tables live inside of the same database and maybe even inside of the same schema, but in
order to break things down and follow something like the Single Responsibility Principle, we don't want one giant DbContext that
can do everything for certain applications. Sometimes we want to break that database up into smaller pieces. So, you can certainly
have multiple DbContexts in a project that point to the same database, just different sets of tables. So, how do we know what tables
this DbContext uses? Well, any time I have a public property on a DbContext that is of type DbSet of T where T represents a
generic type, DbSet is a type that tells the Entity Framework you areworking with a table of data that should have the shape of a
particular object that you have defined in your project. That object's defined by the generic type parameter for DbSet. If I say I have
a DbSet of type Restaurant, that tells the Entity Framework that somewhere inside of a database that I will point this to with the
connection string, there is a table that contains data that can populate Restaurant objects. Somewhere there is atable that will contain
records with an Id property and a Name property and a Cuisine property. When I query that table, I can map the data that comes
back into this class, Restaurant. Now there's many things that you can do with the Entity Framework to customize the configuration
and topoint the Entity Framework at different features and different tables and renamed columns and so forth. I'm not going to
go into any of those topics with the Entity Framework. I just want to make you aware that the framework is flexible enough to work
in different ways. But by default, ifI'm querying data from my SQL Server and I'm bringing back a result set that includes columns
named Id and Name and Cuisine, that is the simple mapping that the Entity Framework will do. So if it brings back something
named Cuisine in a column, it's going to map the data in that column into a collection of objects that have a Cuisine property. It's
going to move that data into the Cuisine property. This is what the Entity Framework does, and it's what we're about to see in just
a bit. Also, if I name this property Restaurant, then by default the Entity Framework is going to assume there is a table named
Restaurants in the database. Again, that is a convention that you can change through explicit configuration. But just by specifying
that I want a DbSet of Restaurant with the name Restaurants, I've already told the Entity Framework that there should be a table in
the database named Restaurants. In that table, we should have columns with the names of Id, Name, and Cuisine. The Entity
Framework will also, as we'll discover, use these data annotations to get even a little more information about the data model that
we want to use in the database. So if I say something is Required, that's like going into SQL Server and saying that a column is not
nullable. If I say something has a MaxLength, so that's another validation attribute that we haven't looked at yet, but if I say a name
a maximum length of 255 characters, that's enough for the Entity Framework to say oh, this Name column in the database, if I have
to create it, if it's up to me based on the information I know, I will create thatcolumn with a maximum length of 255 characters
because that matches the entity definition that you've given me. In fact, this is what we're going to do. We're going to use our
definition for Restaurant and our definition for this DbContext to allow the Entity Framework to create a database for us so we don't
have to write SQL statements to issue create database or create table calls and define columns and so forth. We can also use the
Entity Framework to work with existing databases that are out there. These are the types of topics that are covered in detail in
other courses on Pluralsight. Julie Lerman has loads of courses on the Entity Framework here. So, go look for those if you
want more information about the capabilities and features beyond what I'm showing you here.

Creating a Data Access Service


Now that we have a DbContext in our project, let's use OdeToFoodDbContext to implement a version of the
IRestaurantData interface that will store and query data in a relational database, SQL Server. I'm going to place this functionality
into a new class, a new service. Let's call this the SqlRestaurantData to differentiate this from the InMemoryRestaurantData,
the data that's just held in-memory. This new class will be a public class. It's going to implement IRestaurantData. I'm going to use
Ctrl+period in Visual Studio to go ahead and generate all the methods that I need. Now we just need to perform the simple
operations inside of each method. These are going to be very similar to the in-memory operations that we have, because remember
the goal of an object-relational mapper, like the Entity Framework, is to make data in a database as easy to work with as data that
you're just holding in an in-memory collection. In order to do that, I'm going to need to construct a new instance of a DbContext. In
order to perform this work though, I'm going to need an instance of an OdeToFoodDbContext inside of this class. The question is,
do I explicitly construct a new instance of OdeToFoodDbContext inside my SqlRestaurantData constructor and save that instance
into a private field, or do I ask my application and ask my environment to pass me an OdeToFoodDbContext? That is the
approach I'm going to take. Because we're usingAutofac, because we're using dependency injection, because we have that
nice Inversion of Control container, I can simply ask for an OdeToFoodDbContext. It will be given to me and
configured elsewhere. I'm going to take that instance and save it into a private field called db. And now we can perform our work
inside of these methods. How do you add a new restaurant so that it gets saved into the database? Well, the first thing you can do is
walk up to the Restaurants DbSet property on the DbContext, then you simply tell that DbSet that you want to add thisrestaurant. At
this point, nothing will be added to the database just yet because the DbContext implements what we call the Unit of Work Design
pattern. The unit of work records what changes that we want to apply to a database, what things do we want to add, what things do
we want to delete, what things do we want to update, and then nothing actually happens until we tell that unit of work to commit or
save the changes that I've requested. When I call SaveChanges, this is the point where the DbContext says oh, I saw earlier that
you wanted to add a new restaurant, let metake that data and use it to construct an insert statement for SQL Server and then execute
that statement in a transaction with any other changes that you might need. Now if that is all the Entity Framework did, that would
be good enough, but the Entity Framework is one step further. It will look at this restaurant and see that every restaurant has an
ID property. By default, the Entity Framework is just going to assume if you have aproperty named ID, you probably want that to
represent the primary key for this particular entity. Again, all these features and behaviors are configurable with the Entity
Framework. But by default, the way we have written the Restaurant, it has an ID property that is of type int. The Entity Framework
is automatically going to make that a primary key when it creates a database and a table to store restaurant information. Not only is
the Entity Framework going to make that property a primary key in the database, it's also going to make that column in the database
an Identity column, which means that every time I insert into the Restaurants table, SQL Server will generate an ID for that
restaurant. Now what the Entity Framework will do is bring that identity value back and populate my Restaurant object with that
new ID value. So I will know the ID of a restaurant as it exists in the database immediately after calling SaveChanges, and there's
no other work I need to do. That's one of the nice benefits of using the Entity Framework. Now that we know that, let's implement
the Get method. So previously, we just had an in-memory list that we could query with LINQ statements. The way to think about
this scenario is we now have a DbSet of restaurants that we can query with LINQ statements. If I want to find the FirstOrDefault
restaurant, I can still use that LINQ operator and I can say given a Restaurant, r, let's make sure the Id of that restaurant matches the
incoming Id parameter to this method, and I will return that restaurant or I will return null if we don't find something with that Id. If
we want to get all the restaurants, again I can go to the Restaurants DbSet and I could just return that DbSet directly, because yes,
DbSet does implement IEnumerable of Restaurant. I can also throw in some default behaviors like a default sort order. So I could
use an order by statement. And, yes, I can use the fancier LINQ syntax that says from r in db.Restaurant, I want to order by r.Name,
so that will order by therestaurant name in ascending order, and I want to select each restaurant. So that query syntax works
perfectly well too. How do we update a restaurant? This is a bit of an interesting scenario with the Entity Framework. One way to
approach this update scenario is to first retrieve a restaurant from the database. I could say restaurant equals Get some restaurant by
id, and I would now have a record from the database. The Entity Framework, being a unit of work, implements a feature known as
change tracking. In other words, if I then go to the restaurant and I change something like the name to be an updated value from
this restaurant or otherwise set some value into the restaurant, the Entity Framework is smart enough to detect that something has
changed in the name property of that particular restaurant with that particular ID. And so later when I call SaveChanges on my
DbContext, the Entity Framework will be able to look at the changes and issue update statements to reconcile all thechanges that I
have made to restaurants that are in-memory and push those changes into the database in a transaction. However, this isn't always
the best approach to simply retrieve the restaurant from the database, push my changes into that object, and then call
SaveChanges, that's not always the best approach if I have multiple users in an application that might be updating the same
restaurant. In that case, you want to look atimplementing a feature known as optimistic concurrency. I'm not going to
cover optimistic concurrency in this course, but I will show you the code that you should write to update a restaurant if you want to
have and implement optimistic concurrency in the future. Without optimistic concurrency using the approach that I've shown you
here, with this approach the last user to click the Save button is going to be the user that writes into the database and saves their
changes, so the last person in with updates will win. With optimistic concurrency, you can have a check that makes sure
this restaurant hasn't changed since the user read the restaurant data. It helps to prevent situations where one user overwrites another
user's changes. You can detect those scenarios and handle them a little more gracefully. In order for optimistic concurrency to work,
there has to be a number of things in place, but you also have to write code like this. You have to write code that walks up to
the DbContext and says I have a new entry for you to track. So, this is a little bit different than going to the Restaurants DbSet.
Instead, I'm going to the DbContext and saying here is an object, you're going to be able to figure out that it is of type Restaurant.
What I want to do is make you aware of this object, make you aware that this is an object that should already live in the database.
You can figure out what table and what the key is because you know about all the primary keys on my entities, you know what
tables they map to, and I'm telling you about this object so that you can start to keep track of it and start to track changes.
Furthermore, I'm going to add one more line of code here that says the current state of this particular entity is that this entity is in a
modified state, and I'm going to remove the namespace prefix that is placed here and use Ctrl+period instead to add ausing
statement because I think that makes the code a little bit easier to read. Of all the operations we've performed, most of the operations
are very simple. They map to exactly what happened when we were working with in-memory restaurants. The update scenario is a
little bit different,but we're essentially going to the DbContext saying here's an object that should already be stored in the
database, but what I'm about to do is give you that object in a modified state, so it has changes that need to be persisted. So when I
call SaveChanges, the Entity Framework will issue an update statement for this restaurant record and make sure the data in the
database matches the data that is in the properties of this object. That is what should happen. Now that we have
our SqlRestaurantData in place, we can now work on configuring our application to use the SqlRestaurantData and configure
our application to give the right connection string to our DbContext.

Configuring a DbContext
The first bit of configuration that we need to add or change in our application is the configuration of our container. You might
remember we did that earlier in the course. It happens inside of the App_Start folder inside of ContainerConfig.cs because we will
no longer be usingInMemoryRestaurantData when a piece of the application is looking for an IRestaurantData. Instead
of InMemoryRestaurantData, we want to change this to SqlRestaurantData. So we'll talking to a real database just by making that
one little change here. But I also want to change this line of code that is saying give me just a singleton instance for the entire
application, for the entire life of the application. We needed to do that with the in-memory data so that every time I made a request
to the application, I would be looking at the same list of restaurants. I was doing that just for development and testing here. But now
that I have a real DbContext and I'm using a real database, well, first of all, I do not want to be single instance because a DbContext
is not a thread-safe class. So I don't want to have a single DbContext for the entire application. In fact, I wantsomething almost the
opposite. I want my container to create an instance of SqlRestaurantData for each HTTP request. That's usually a pattern that you
follow for any component that implements a unit of work. You're going to create a particular component and allow it to be around
for a single HTTP request where you're performing all these numbers of actions for a particular user and a particular request from
that user. But then when that request is over, you can throw that instance away and you can create a new one for the next
request. That's the safest and easiest way to use a DbContext, which is really what we're using behind the scenes
of SqlRestaurantData. But I also need to register the type that mySqlRestaurantData needs injected into the constructor, which is
that OdeToFoodDbContext type. So we're going to register that DbContext and also make that an InstancePerRequest scoped
object. That configures the services and the components that I need inside of the application. Nowthe question is, when the
container brings in OdeToFoodDbContext object to life, what database is that context going to try to talk to. Again, I'm going to
follow some conventions that the Entity Framework uses to configure this DbContext implicitly. However, once again, I just want
to pointout that there is as much flexibility here as you need to perform whatever customizations you need. There's all sorts of
different ways to overload methods and provide different constructors for a DbContext that will allow me to dynamically connect to
a database for example. But all I want to do is add a connection string to the Web.config file because it's connection strings
that ultimately this DbContext needs. The DbContext needs a connection string. It uses that because the connection string will tell it
what server to connect to, what database in that server, what username and password to use. All of that can happen from this
configuration file that we looked at earlier in the course, the Web.config file. What I want to doinside of here is add a new section,
a section that I should have IntelliSense for, a section called connectionStrings. What I want to do here is add a new connection
string to my Web.config and add a connection string that has the same name as my DbContext because what the DbContext will do,
by default, unless I tell it to do something different, is when I construct an instance of this class, it will go out and look in
the connectionStrings configuration for a connection string name that matches this class name. So if inside of Web.config I say let's
add a connection string with a name of OdeToFoodDbContext, that will be the connection string that my DbContext will use. And
then there's just two additional pieces of information that I need to provide, one is the connection string, which will tell my
DbContext what server and what database to go to, and another piece of information I need to provide is the provider name. This
tells the Entity Framework essentially how do I connect because there's different providers for different database types. So, there's
one provider for SQL Server, and there's a different provider for SQL Server Compact. And then other individuals and other
companies have written providers for things like IBM's databases and Oracle's databases. But what I want to use is the provider for
SQL Server. So I just need to specify a name here, which is the name of that provider, and the name of that provider is
System.Data .SqlClient. That's the provider my DbContext will use. Now I just need the connection string. Now there's various
websites and pieces ofdocumentation that will tell you how to build a connection string. You can also use something like SQL
Server Object Explorer and right-click on a particular server and go to Properties. Over here in Properties, there should be a
General property, which is the connection string for this particular server. In this section here that I have a difficult time mousing
over because there's some strange video artifacts that occur, but this section, if you want to copy this out of here, will give you the
exact connection string that you need to connect to that server, and you might just need to tweakthe database name. But let me write
this from scratch for you. I'm going to say that the connection string is, and we start with a Data Source, so I say that the Data
Source, which is really what server or what instance am I connecting to, is going to be LocalDb\MSSQLLocalDB. Once we have a
connection to the server, we then need to look at what database on that server to connect to because there can be multiple databases.
The database is known as a catalog. So we're going to say that this is the Initial Catalog. I want the name of my database to
be OdeToFoodMVC. Let's call it OdeToFoodMVC. I also need to provide the credentials that will be used to establish a login
and connect to that server and that database, or I can use a setting known as integrated security, which is a fancy way of saying just
use the credentials that are part of the current user process to connect to the database. Since when I'm running my application using
Visual Studio, that application is essentially running with my login and with my credentials, I will be able to connect to that
database and I'll be able to create databases and query data. But let's set Integrated Security=SSPI. With that, I should now be able
to save all files and perform a build. Let's come back in the next clip and test out the application.

Exploring the New Database


With our code and configuration changes in place, I'm going to do a build of the application and then let's come back out to the
browser and issue a refresh for /Restaurants. What I want to see is a list of all my restaurants. It's going to take a little bit of time,
this first refresh, after configuring the Entity Framework. Now I see that I have no restaurant, but that's actually a good sign. It's a
good sign because there is no error message, and the fact that I have no restaurants makes sense because before I refreshed this
page, I did not even have a database to store restaurants in. You might be wondering what sort of magic is happening behind the
scenes where I do not have an error because we clearly saw earlier in this module when we looked at the instance of LocalDB, there
was not a database that had the name of OdeToFoodMVC. But now let's come back to Visual Studio and go to the SQL Server
Object Explorer. I can still see my list of databases here. I have not refreshed this list, but let me right-click the server and say that I
want to Refresh. Now under the list of available databases, I can see OdeToFoodMVC. So, this is something that the Entity
Framework will do for you. Again, this is a configurable feature. If you do not like this behavior, you can turn it off. But by default,
when I tell my OdeToFoodDbContext that I want to connect to this server and connect to this database, which was
OdeToFoodMVC, if the Entity Framework does not find that database, the Entity Framework can and will create that database.
That's the default behavior. The Entity Framework will use my DbContext-derived class definition and my entity definitions
to create a schema inside of this new database, OdeToFoodMVC. So, you can see Ihave two tables. One table is MigrationHistory.
That's a table that Entity Framework uses for bookkeeping purposes to figure out when the schemaneeds to change and when the
schema needs to be updated. And then there's a Restaurants table. Because I have a DbContext that has a DbSet of type Restaurant,
the Entity Framework knew it needed a table to store restaurant information. Since the name of my class was Restaurant, the Entity
Framework pluralized that class name and created a table named Restaurants. I can expand this table and see that I have a few
columnsinside. These columns will exactly map to the properties of our Restaurant. So I have an Id property, a Name property,
and a Cuisine type. Notice the Id is a primary key. It's of type integer, and it's not nullable because the Entity Framework, just by
convention, looks at my class definition and says oh, if you have a property named Id, you probably want that one to be the primary
key. Again, that's a behavior that you can change and that you can configure, either programmatically or through the use of
metadata and attributes. Speaking of metadata, notice that the Name property is of type nvarchar 255 and it's not nullable. That's
because of the data annotations that I have in place on the Restaurant type. Remember, we told both the MVC framework and now
the Entity Framework too respects these attributes. We told these frameworks that the maximum length of this property is going to
be 255 characters. That's where the nvarchar 255 came from. We also said that this field is a required field. So the Entity
Framework decided to make this column not nullable in the database, otherwise we would have had a column that is nullable and of
type nvarchar max, so it could store the largest possible string. Now since the Entity Framework just created this table, there's not
going to be any restaurants inside. So if I come to the home page of the application, I can see there are 0 restaurants in the database.
So let's go ahead and create a new restaurant. I want to call this Scott's Pizza. We'll set the type of food to Italian, and I will say
Create. Let's also go back and create a secondrestaurant at least. We will call this Mango Grove. I'll make sure the r is lowercase. I'll
set the Type of food to Indian. Click Create. Now if I come to the list of all restaurants, I can see two of those inside. If I come back
to Visual Studio, I should be able to open up SQL Server Object Explorer. Let me right-click on the Restaurants table, say that I
want to View Data that is inside. There are the two records representing the two restaurants that I have created in the application.
Now that we have our application talking to a database, it's time to implement yet another feature. That feature would be the delete
feature. We'll do that in the next clip. But this might be a scenario where you want to try this on your own first.

Implementing a Delete Feature


Here's how I would implement the delete feature. First of all, just like we had with edit and details, I already have a link associated
with each restaurant that points to a particular controller action. In this case, it is /Restaurants /delete/1. So we're pointing to a
delete action, but that delete action doesn't exist. Just like with the create and edit scenarios, we're going to be modifying data. So
we're going to use a pair of actions to implement this delete feature. First, I'm going to close all the documents here to clean things
up a little bit. Let's come down and open up ourRestaurantsController. I want to scroll down to somewhere underneath of
edit because once again we're going to need an action that responds to a GET request and an action that responds to a POST
request, so one action that will present information to the user, we want to make sure the user does want to delete this restaurant. We
will confirm this action with them. When they confirm that delete operation that they want this to gothrough, we're going to use a
form to send an HTTP POST to this application to perform the deletion in the database using the Entity Framework, because
remember, we don't want to modify anything during a GET request. So we don't want the GET version of a request to delete a
record even though that GET request could contain all the information that we need to delete a restaurant because all we really need
is the Id of that restaurant. What we want to do when the user clicks on that Delete link is send them to a page asking them if they
are sure they want to delete this restaurant. And when they click Yes, that's when we will do a POST to this application and handle a
delete action that uses our data service to perform the deletion. First, let's write a delete action that responds to HTTP GET that
will return an action result. We will call the action Delete and it will take an id parameter. What we can do is go out and look for
that restaurant so we can pull up more information about it. I want to go out and get the restaurant that has this ID. If that restaurant
comes back as null, then we could return a 404 error to the user. We could also return the NotFound view like we did with the
Details action earlier. Really, it depends on you and your application and your users, which of these paths that you choose.
But otherwise, I want to return a new delete view that will display this restaurant information. Let's go ahead and scaffold that.
Right-click inside of the action. I want to Add View. The view name will be Delete. The template will be the Delete template we
will choose. The model class is of type Restaurant. This is very similar to what we've been doing in this course, filling out the
scaffolding information. Now one difference is that this Delete template wants to go directly to a data context class. We're going
to ignore that and just click Add. That should give us just the Razor view markup that we need to display, Are you sure you want to
delete this, and display the restaurant name to the user. That's really all the user interface that we need. And then notice that we will
have a form. So we will have a form that performs an HTTP POST operation back to /Restaurants/delete /whatever identifier was
needed. This form will include an anti-forgery token. That is important. All we really need inside ofthis form is an input, which will
be a button, which will be the Submit button. So when the user clicks on this button, the browser will do a POST back and we will
delete that restaurant. Let's implement the version of delete that will handle an HTTP POST operation, and we will also validate the
anti-forgery token. I do want to point out because I have gotten this question in the past, why wouldn't we delete using an HTTP
delete method? That's because browsers and the HTML specification, they really only think in terms of GET and POST. So you get
a resource when you read it, you post a form where you submit values and change data on the server. When you're
building applications whose primary job is toproduce HTML and read forms, you're really just using two of the available
HTTP verbs. Those verbs are GET and POST. It's not until you move into the world of web APIs where you start using some of
these other HTTP verbs, these HTTP methods, methods like patch and put and delete. Yes, if I was building an API for other pieces
of software to call over HTTP and I wanted to have a controller action that would delete something, delete some resource, then yes,
I would say this only responds to an HTTP delete message. But since I expect this endpoint to be invoked by a browser through a
form, then I really need to respond to an HTTP POST request. So this is going to be a delete action that returns an ActionResult. It's
named Delete. The only parameter that we need in this scenario is just the id of the restaurant that we want to delete. But now we're
in a bit of an awkward situation that the C# compiler is unhappy because we really need a delete action that responds to a GET
request and a delete action thatresponds to a POST request. In both cases, all we need is an ID parameter. But the C# compiler is not
going to be happy because we have two identical methods with the exact same signatures. When this happens, you will sometimes
see people take an additional parameter, a parameter of type FormCollection. What FormCollection can do is encapsulate the name
value pairs that the browser is posting in a given form, but it can also be used to sort of a throwaway parameter in that it's safe
to have here as a second parameter. The MVC framework will populate that formcollection, but I'm not going to use that parameter.
It's really just there. So I can overload the delete method and have these two separate methods. Now what I need to do is delete that
restaurant using my data access components. But we have no way to delete a restaurant currently, so we're going to have to add that.
With the IRestaurantData interface, I'm going to come in here and say let's define another method named Delete that takes an
id parameter, and we'll delete a restaurant. Now I just need to implement that particular method both in
myInMemoryRestaurantData, as well as my SqlRestaurantData. So, using Ctrl+period, I'll generate that method here inside of my
InMemoryRestaurantData. I should find it down here at the bottom. How do we remove a restaurant from an in-memory collection?
Let's go out and get a restaurant by the id. If the restaurant is not equal to null, I'll simply remove it from the list. So, restaurants,
that in-memory list that I'm maintaining, let's remove the object with this reference, so that restaurant object. It's a very
simple operation in-memory. It's also a very simple operation with the DbContext. Let me again press Ctrl+period, generate
that method, scroll down here until I find the Delete method. I'm also going to go out and find that restaurant. I just want to show
you that in addition to doing a LINQ query, like FirstOrDefault, there's also a special method on a DbSet named Find where all I
need to do is pass in the values that represent the primary keys for that particular entity. The DbContext will go off and find that
restaurant in the most efficient way possible, perhaps even use a cached version of that restaurant that italready has. Remember, the
Entity Framework can be smart about the types of objects that it caches because it knows the primary key, the primary identifier for
everything that you place into and pull out of a database. Once I have that restaurant, I can then walk up to my DbSet and tell it to
remove that restaurant from the database. Once I do that and call SaveChanges, that will issue a delete statement to the database and
thatrestaurant record will be removed. Let's do a build in the application. I do have an error because now that we have that delete
implemented, I can finish placing code in my delete action, which I hadn't done as yet. So let's do a db.Delete, pass in that id. Now
what view should we display? Well, I cannot go to the details for a restaurant that I just deleted. Let's do a RedirectToAction and
just return the user to the list of all restaurants, so back to the Index action. Now I can do a build. The build is successful. Come out
to the application, let's do a refresh of all the restaurants just to make sure everything is still operating. Now, I finally have
an application where my restaurants will stick around between a rebuild and a refresh, and I now also have the ability to delete a
restaurant. Am I sure I want to delete Mango Grove? Yes, I want to delete Mango Grove. Now Mango Grove is gone. I can check
on the home page and I can see there's just one restaurant in the database. Now we have an application using the Entity Framework
to work with Microsoft SQL Server and store our restaurants persistently in a database. You can see just how easy it is to workwith
the Entity Framework. But I really did just scratch the surface of the capabilities of the Entity Framework. So a lot of the features
that I showed you, how it automatically creates a database and automatically generates a schema, how it automatically looks for a
connection string with a given name, all of these behaviors, as I mentioned previously, are behaviors that you can change and you
can influence either through code or through configuration or through metadata. And although the scenario I've selected is just a
simple scenario to get us started, that is we're managing essentially just one entity, you can also manage more complex scenarios
and scenarios where there are relationships. So I can haverestaurants with a collection of employees where an employee can be
composed from complex data types like address and have a phone numbers collection. But you can find all of that in other courses
here on Pluralsight. What we're going to do is move on in the next module to the topic ofRazor views to really understand what's
happening here at the UI level some more.

Razor Views
Understanding Razor Syntax
Hi, this is Scott. And in this module, we're going to take a closer look at the Razor views that our application uses to render HTML
to the browser. We've already learned a bit about Razor views and HTML helpers and where views are located, but there's still a
few more details you should know for day-to-day development. For example, if I come over into Visual Studio, let's open up the
Index view for the RestaurantsController. So this is the view that renders the list of restaurants for the user to see. And you already
know that @model is a directive, so this is more of an instruction for the compilers and the tools to know that this view is going to
work with a collection, an IEnumerable of Restaurant, that's the model. And then Model with an uppercase M is the model property
of this view. This gives me access to the model object that the controller has built for this view.And I can access that property inside
of a statement or inside of an expression. So when using the at sign and writing C# code that includes an opening curly brace,
I'm really creating a block of C# code. And I need to write proper statements inside of that block. So an example would be up
here at the top. This is a block of C# code. This can be full of many statements. In fact, I can even declare variables inside of here
and say x = 2 + 3, and I need to end every statement with a semicolon, just like I would if I was writing regular C# code inside of
a .cs file. But I can also use the at sign to create an expression, so something like @ Model.Count, which is not a full statement. All
I want to do is write out the number of restaurants that I know about, so @Model with an uppercase M again is accessing the
property of this view. So I'm working with an IEnumerable of Restaurant here, and the syntax is telling the Razor View Engine,
evaluate this expression, Model.Count, and place the result as a string into the output. So the number 2 or the number 1 or the
number 10 or the number 100, however many restaurants we have, should appear right at this location after the closing h2 tag and
before this opening paragraph tag. This goes right into the output stream. And anything that you do in Razor by default will be
HTML encoded to help prevent cross-site scripting attacks. If that's not something you want to do, if you want to have some
expression or takesome value or some string and send that into your output without HTML encoding, one way to do that is to use an
HTML helper, the Raw helper. So inside of here I can have a string that includes HTML markup, and it will render HTML into
the output stream, but you have to be careful with that one because of cross-site scripting attacks. Now we've already seen in this
course when I have an at sign and I'm writing a C# statement that has an opening curly brace, and just like in a regular C# file I need
to match that with a closing curly brace somewhere, and in between I can have statements and expressions, but you'll notice how
easy it is for Razor to transition between C# mode and HTML mode. Basically when Razor getsto this character right here, it
doesn't treat it as a C# less than operator, it treats this as a hunk of HTML that has to be emitted as is back to the client. And that's
just some intelligence or heuristics that are built into the Razor parser, but they don't always work. If I wanted literal text to appear
here, so I'm going to have something inside of a foreach loop that is not immediately an HTML element, if I just want to write
out some text, well, that one is going to be a bit of a problem because the Razor View Engine is going to think I'm still writing some
C# code. And it's going to go looking for a namespace or a variable or something named text and it's not going to find that. If you
ever find yourself in that situation, you can use the at sign and a colon, which is another way of telling Razor this is a bit of static
text that needs to be sent down to the client in the output, so render this into the HTML. You can also run into some other
edge circumstances with the at sign. So for example, what if you wanted to output anemail address right here? So I want to write
scott@ OdeToCode.com, and the question is will the Razor View Engine interpret @OdeToCode as some bit of C# code? And the
answer is if we run this application and I pull the new window over here onto the screen, but no, it turns out there's a special case in
the Razor View Engine where Razor will recognize an email address, so something of the form text@something, Razor will think
of that as an email address and not try to interpret the at sign as switching into C# mode. But what if I wanted to write out
my Twitter handle? So what if I wanted to write @OdeToCode? So the syntax highlighting inside of Visual Studio is going to give
this one away in that Razor is going to try to interpret that as a C# expression that needs to be rendered. And because this name,
OdeToCode, doesn't exist in the current context, I'm going to have a compilation error. However, I can escape the at sign, so
anytime I write @@ and then have some expression, Razor will say, oh, you must want to output literally the at sign. So that's how I
can output a Twitter address. And what if had some situation like I wanted to output scott@ OdeToCode.com and then something
off a model? So let's say I wanted to say scott@ OdeToCode.com and then some number like 1 or 10 or something that was derived
from my model, for whatever reason, but obviously Razor has already determined that this is some sort of email address, so it's not
going to evaluate Model.Count as an expression. However, anytime you're faced with that situation, if you use the at sign and then
place your expression inside of parentheses, like I have just done here, that's an explicit way to tell the Razor View Engine I want
this treatedas an expression, so please evaluate Model.Count and place that result into the output, so now I can have the number
1 because we only have one restaurant in our list. And these are some of the little details about Razor that I wanted to share with you
to hopefully make your day-to-dayexperience with Razor a little bit better. And now let's go into some larger topics about Razor.
Like, for example, how does the view that I'm writing, the Index view, how does it automatically plug into the layout view which
controls the rest of the markup that we see appearing here, forexample, the menu for the application? How does that work? We'll
talk about that next.

Managing Page Structure with Layout Views


So what is it about this Index view that allows this view and this markup to render inside of some larger view that also presents an
application menu and a header and a footer and so forth? Well, ultimately what has to happen is that someone has to set the Layout
property of this particular view. So just like every view has a model property that I can use to access the model object, I also have
a Layout property that I can set to tell theMCV framework and the Razor View Engine what layout view do I want to use. So before
we set that, let's also clean up this experiment a bit. I'm just going to remove that bit of code. And then I'm going to say that I want
to set the layout property to, let's just use something called _TestLayout.cshtml. So is this a file that exists in the application?
No, this file does not exist. But when I come back and I refresh the browser, we'll see that this is the layout page that our Index view
now wanted to use, but the MVC view engine will throw an exception and tell us that Views/Restaurants/ _TestLayout.cshtml is not
a file and is not a layout page that I could locate, thus we're just going to throw an exception. So by setting this Layout property, you
have complete control over the layout view that this Index view is going to use. So I can remove this line of code, and clearly
something is setting that Layout property by default because now I'm using a layout view that we've looked at before, the layout
view that is in the Shared folder. But before we look at the little bit of magic that makes that work, I also just want you to know
that you can explicitly set the layout view inside of a regular view if you want to override the magical default for your project. In
fact, you can say Layout = null, which is a way of telling the Razor View Engine, I want to render this view without using any
layout page, so now we have just the output from our Razor view. This can be very helpful for those applications that are using a lot
of client-side JavaScript and you don't want a full HTML page to come back from the server, you just want pieces and fragments of
HTML that represent the bits that need to be updated on the screen. And this is what our Index view would look like if it wasn't
plugging into a layout view. So not only is there no menu, there's no header, there's no footer, there's also no CSS files, so there's no
Bootstrap framework which makes this HTML markup appear and render very differently in the browser. But coming back to
Visual Studio, if I remove this line that says Layout = null, so I take the default layout page from my application, that's going to be
the layout page that is in the Shared folder. How does that happen? That's the topic for the next clip.

Settings Layout Defaults with _ViewStart


Inside of our application, inside of the Views folder, one of the files you might have noticed inside of this folder is
the _ViewStart.cshtml file. This file is interesting because it doesn't contain any HTML markup, it simply contains a single C#
statement that says Layout =. And it is this file that is responsible for setting the layout view, the default layout view, for all the
other views in the application. So _ViewStart.cshtml is a special file that the Razor View Engine will go looking for. And any code
that you place inside of _ViewStart.cshtml in this code block will effectively execute before the code blocks inside of your
Razor views. So think about it this way, when the RestaurantsController says go render the Index.cshtml view, yes, the Razor
View Engine will find Index.cshtml here, but before it starts executing that particular view, it will first execute the code inside of
any ViewStart file that it can find in that folder or any parent folder. So a ViewStart file is very hierarchical. When you place it into
a folder, and here it's inside of the Views folder, it will effectively apply to all of the folders and all of the views inside of
the subfolders beneath it. So in other words, I could have also had a special ViewStart file inside of just the Restaurants folder or the
Greeting folder. But this bit of code will execute to say set the layout property for this particular view to _Layout.cshtml, and then
the Razor View Engine can go in and start to execute the Index view. And the Index view, if it has a layout statement here, that
might be overriding what the ViewStart is doing, so we did see earlier that I can set the layout to null, but because ViewStart gets to
execute before my view, that gives me a nice default setting where I will use this _Layout file unless I specify otherwise. So this bit
of code applies to all the views so that I don't have to have this bit of code inside of every single view inside of the application. And
that's how we can effectively have a default layout view of _Layout.cshtml.

Using the ViewBag


Let's look at the layout view that we are using, _Layout.cshtml, in the Shared folder. This layout view will contain, like most layout
views, the HTML structure that every web page needs to put in place in order to be a valid HTML document. So for example, it is
the layout page that can take care of setting the DOCTYPE, and it's the layout page that can take care of the head tag for our HTML
document. And our head tag is going to contain things like the common style sheets that we use all throughout the application, as
well as metatags to set the character set, as well as the viewport. And then there's an interesting bit right here where the layout page
wants to set the title for the page. So this is interesting because every view in the system is going to want to set its own title. So how
does a view like Index.cshtml provide the title information for the layout page which is actually responsible for rendering the title
tag and setting the title in the browser? Well, in ASP.NET MVC this is done through a data structure known as the
ViewBag. ViewBag is a property, just like layout and model, that I can access inside of a layout view or inside of a regular view. In
fact, if we open up Index.cshtml, we will also see the ViewBag property that is being accessed here. And ViewBag, if I hover over
this, you'll see it is of type dynamic. So this is a dynamically typed property that I have available from my view, and because it's
dynamically typed, I can basically treat ViewBag like a dictionary of key-value pairs. So anything that I want to add into the
ViewBag, I can add into the ViewBag, and anything I want to retrieve from the ViewBag, I can just ask for by using the dot
operator and trying to get into the ViewBag. So for example, I could say ViewBag.Message = Hello!, and then somewhere else in
the system, like for example inside of the layout view, I can try to access thatmessage, so down here I can say ViewBag.Message, so
somewhere in the body of this layout page, somewhere inside of our div that contains our container. And now if I come back to the
browser and refresh, you can see the Hello! appear down here, so I have effectively transmitted some data from my content view,
which is Index.cshtml, into my layout view, which is _Layout.cshtml. Of course my layout view has to be a little bit careful because
not every view in this application is providing a message property on ViewBag, but for right now I just want you to focus on the
larger picture, which is ViewBag is this dictionary of items where I can just throw things in and pull them out somewhere else, like
inside of the layout view. So why do we use the ViewBag to set the title for our web page? Well, because I am sharing the same
ViewBag between this layout view as I have in my index view, that's pretty clear from the demo that I just showed where I showed
you the message, but why couldn't we have, let's say, for example, a title property? Why can I not say @ Model.Title? Well, I
can access the model property of a view from the layout view, the problem is inside of this layout view I have no idea what
the underlying model is going to be, because the model object is going to be different for all these different views that are inside of
the Restaurants folder. So with the Index view, the model is an IEnumerable of Restaurant, for the Detailsview, the model is a single
restaurant, and my Layout view has to work with all those different types of views. So instead of trying to work with a model object
and perhaps coming up with some base class that represents all the models in the system, ASP.NET MVC makes
passing information between a regular view and a layout view really easy by providing this ViewBag data structure. And so
ViewBag is one technique you can use when your layout view needs to display or render something specific to a view. So this is the
title that is specific to the index view, but it does this in a way where the layout view doesn't become coupled to the index view. So
we're just going to output whatever is in ViewBag.Title, and any view in the system has the ability to set that property on the
dynamic ViewBag.

Adding Flexibility with Layout Sections


Somewhere inside of every layout view you will find a call to the method RenderBody. This is the point where the Razor
View Engine knows to render the primary content view that was requested by the controller. So when the controller says please
render the index view, and the index view either through ViewStart or through its own block of code says render the layout view,
then the Razor View Engine starts building this HTML to send down to the client, and when it finds RenderBody, that's when it
will essentially jump back into the index view, produce all the HTML that the index view requires, and all of this dynamic
output will be placed here where we have the call to RenderBody. We've seen how this worksthroughout the application. Every time
we create a new view, whether it's a delete view or a details view or an edit view, we only need to write the HTML that is specific to
that feature, and the layout view takes care of building the rest of the page. But what happens if we have a view that wants to plug in
more than just the body of a content? So perhaps we have a view that wants to customize not only the body content area that is
inside of this div, but let's say it also wants to plug something into the footer area, or perhaps I have a view that includes
some custom JavaScript and I want to render that JavaScript as late as possible in the page, so right before the closing body element,
and right here after the layout page has placed some other script files into the page. So this script helper helps me render script tags
so that I can place jQuery into the page and Bootstrap into the page. And then you'll see this call to RenderSection. So it is
RenderSection that will allow me to perform this behavior where I can define additional sections inside of this layout view that
the content view can render into. So for example, imagine I have an application where some of the views in this application need to
render a custom footer or they need to place additional information into this footer. If that's the case, I can invoke the
method, RenderSection, I will pass in the name of the section. Let's name this section the footer area, and then I can make this
arequired section or an optional section. So I'm going to say required is false because currently there are no views inside of this
application that have a footer section defined. So now when I do have one of those views that wants to place something here into the
structure of the page into the footer section, how do I produce the output that appears here? Well, let's save the Layout view and
come over to the Index view. And somewhere inside of the Index view, it can be at the beginning or at the bottom or somewhere
in the middle, I can use the @section directive to tell the MVC view engine now what I want to do is render the following bit into
the footer of the Layout view. So let's just have some simple markup inside of a div tag that says This is a custom footer. And now
when I save all of my files and come back to the browser, come back to the application and refresh, my content view will render all
of its content where I have the RenderBody call in the Layout view except for the sectionthat is the footer section that renders inside
of that footer section. So coming back to Visual Studio, the @section directive and the RenderSection method can work together so
that your layout page can define a very flexible structure that allows your content views to plug in at different areas.

Reusing HTML with Partial Views


One way to think about the layout view is to think of it as a view that allows you to reuse HTML, because once I have a
head element defined inside of one of my layout views, I never need to use or duplicate or copy and paste that head element and
all of its content into any other view inside of the application. It's just that the layout view also allows me to reuse structure in
addition to markup. So the structure I define with RenderBody andRenderSection is something that will be reused throughout the
application because all my other views have to plug in to that structure that I define. So this is one form of reuse, but inside of
an application, typically you're going to have other scenarios where you want to reuse some of your markup. So let's take this
example. Let's go over into Index.cshtml where we render our collection of restaurants into a table of restaurant information. But
first of all, let's say I want to change this, let's say instead of using a table, I just want to have a series of Bootstrap panels. So
ifyou're not familiar with Bootstrap, if you don't know what a Bootstrap panel is, trust me, it will be very simple. We're just going to
have some slightly different markup, and instead of using a table, we're going to be using divs that have special classes, but it's
going to be very easy to use. The bigger picture here, what I really want you to focus on is that what we really want to do is we want
to define what a restaurant summary should look like. So throughout the application we might have various places where we want
to display summary information about a restaurant like display the restaurant name, in addition alongside the restaurant name, the
summary, we want to display the available actions for that givenrestaurant. So what can the user do to this particular piece of
information? They can edit it, they can look at more details, and they can delete therestaurant. And with the MVC framework
and the Razor View Engine, the way to reuse the sort of markup and presentation logic is to create what's known as a partial view.
Partial views are very easy to create. They're very easy to use. It's going to build on everything that you already know about Razor
views, but ultimately I want my Index.cshtml view to look like the following. I still want to loop through each restaurant or each
item that is in our Model property. So that's going to take each restaurant out of the collection of restaurants that we have and place
that restaurant into item. And then I want to invoke an HTML helper named Partial. What Partial allows me to do is from inside of
this view, go out and say and tell the Razor View Engine I want to render this other view. It's a partial view. It doesn't produce a full
web page, it just produces a fragment of HTML, but that's okay, that fragment is going to go into this content view, which plugs into
a layout view, and put all together, they dodefine an entire web page including the DOCTYPE and the header and the body and
so forth. But I want to go out and render a partial view, and I want the name of that partial view to be RestaurantSummary.
I'm going to take that string and I'm going to copy that into the clipboard because we're going to use that in just a second. But this is
all I need to do to render a partial view. In some partial views that's all the information that you need to provide, but many partial
views will also need a model object that contains the information that they're to place into the output. So yes, it is perfectly fine
to have a partial view that just contains static information, like the address and the phone number for the company. We're also going
to have partial views that need to render a model object, like I want to use this partial view to render each restaurant in my
collection, and that can be the second parameter to the partial method. So I'm going to pass along each restaurant, and this
HTML.Partial helper will go out and find that view, pass along the model object, render that view, and take the resulting output of
that partial view and place it right here into thiscontent view. So this is our goal, create the partial view _RestaurantSummary.
Once we do that, we'll be able to delete this table, but there are some bits of information down here that I want to copy out of here
first, so I'm going to leave the table in place for just now. Let's go and create our partial view. So the location where I create this
partial view is very important. If I create the partial view inside of the Restaurants folder, that's effectively saying here's a
partial view that I'm only going to be rendering from other views in this Restaurants folder. But if I create this partial view in the
Shared folder, that's a way of saying I'm going to reuse this partial view from anywhere, anywhere throughout the application, any
other set of views that might be anywhere inside this application, any view from any controller. I'm going to create the partial
view though inside of the Restaurants folder. So right-click and I want to say that I want to add a view, and I'm going to paste in
RestaurantSummary that I copiedearlier, so with the leading underscore. So the leading underscore isn't required, but again, that's a
convention used by MVC programmers to signify that this is a special type of view that typically isn't used to render a full web
page. So, we've seen _Layout, and now we see_RestaurantSummary, that just means these views are not content views.
they're special views, they are layout view, they are partial views. So _RestaurantSummary, I'm going to start with an empty
template because we're just going to write everything from scratch. It's very easy to do. And I am going to select the checkbox here
to create this as a partial view. That way when I click Add, I will create a file that isn't trying to setViewBag.Title or something else
that I wouldn't need in a partial view. I would need that only in a content view. Now a partial view is exactly like any other Razor
view that you might be working with. Inside of here I can have C# code, I can have C# expressions, I can have statements, I can
also have HTML markup. And I can have @model with a lowercase m to strongly type the model property that is available on this
partial view. So what I'm doing from Index.cshtml now is passing in each individual restaurant to this partial view. So in effect I'm
decomposing a complex model, which is a collection of restaurants, into simpler items and rendering those items with my
partial view, but I am passing along individual restaurants to this partial view so my model would be an OdeToFood.Data
.Models .Restaurant, so an individual restaurant. And now when I go to Model, the uppercase M, the Model property, that's typed as
a restaurant so I can have access to Cuisine and Id and Name. But we need to display this information inside of a Bootstrap panel,
which is easy to create. What I need is a div with a class of panel, and let's make it a default looking panel, so panel-default. Every
panel can have a heading, which is simply a div that has a class of panel-heading, and inside of that let's place an h3 element that
will display Model.Name. So the name of the restaurant, and I'll give this h3 element a class of panel-title. So, panel-default, panel-
heading, and panel-title are just classes defined by Bootstrap to create a UI effect. And then every panel would also have a panel
body, so panel-body. And every panel can also have a panel footer, but that's optional, and the heading is also optional. I'm going to
leave them off. We're just going to place some content inside of panel-body, and the content I want is really just the actions that can
be performed on a restaurant. So let's copy the HTML helpers that create the edit details and delete links, bring them over to our
partial view, I'm going to paste them in here. There is one little fix-up I think I'll need, which, yes, I no longer have an item in scope,
but I can just go directly to model and say this is Model.Id, that's the identifier I want to use for routing, so that's the link that I want
you to formulate. Now let's save our partial view. Let's come back to index.cshtml. I no longer need this table, so I'm going to delete
this from the UI, and I now have an index view that is relatively simple. I'm also going to delete this footer just to clean things up a
bit. That was an experiment just to show you how to use sections. But I have a very simple index view. It takes a relatively complex
model, which is this collection of restaurants, but I'm really delegating the responsibility of rendering an individual restaurant to my
partial view, and now I can reuse and use this partial view from anywhere else inside of the Restaurants folder. So anytime I want to
display aRestaurantSummary. And now if I have everything saved and come back to the application and issue a refresh, the display
might not be that interesting because we only have one restaurant in the entire database, but I do get a restaurant summary that
displays the name of the restaurant in this heading area, as well as the available actions that I can take on that restaurant like editing
the restaurant. And that's an example of usingpartial views with the MVC framework to reuse your HTML and presentation logic.

Passing Data across Requests with TempData


One last data structure that you might find useful inside of a view, inside of any view, layout view or content view or partial view, is
a data structure known as TempData. TempData allows you to store information on the server side that would be around for one
more request it isremoved. So it's very much like storing information in session state except the information will be automatically
removed for you by the MVC framework after the next request. And here's a scenario where temp data can be useful. So let's take
the example where I go into edit Scott'sPizza, and I just want to make a simple change, I'll change the name to Scott's Pizza 2 and
click Save. And now I'm on the Details for Scott's Pizza 2, so I see clearly that I have edited the name of this restaurant. But in some
scenarios that might not be enough. There might need to be some sort of explicit notification or message on this page that says,
thank you, you have successfully saved your information. How would I pass thatinformation from the edit action, which is really
saving this information into the database, over to another request because, remember, we send a redirect back to the browser and
say, yes, you successfully performed a post operation, now redirect over to the details view. There's variousmechanisms that we
could use to pass information along, including just placing some additional information in the query string because we've already
seen with the MVC model binding, we can pass information in the query string or we could pass a message along. But you have to
be always be very careful about passing along information in the query string that then gets echoed onto the page, because
again there's the potential for opening up vulnerabilities and cross-site scripting attack. So let me show you how to implement this
scenario using TempData. Let's come back into Visual Studio and come over into our controller, our RestaurantsController, where
we edit a restaurant, and after we successfully edit a restaurant and before we redirect over to the details action, let's go up to
our TempData data structure, and you'll see that we can work with this TempData data structure much like a dictionary, so it's a
collection of key-value pairs. And I can go into TempData and I can say Message = You have saved the restaurant. And now this
TempData data structure is also something I can use from a view, any view. I can use it from the layout view or I could use it
directly in this Details view because I think as long as the user has successfully edited or created a restaurant, they should be
redirected to the Details view. But if I go into the Layout view, I can display that message after coming from any previous action
or any previous view. So let's do that, let's go over to the Layout view. And somewhere here, perhaps at the top of the page, before
we render the body even. So let's do a check here if there is a message in TempData. So I can write an expression here, if TempData
sub Message is not equal to null, then I have a message, and if it's not equal to null, I want to write that message out into a user
interface. So, let's create a div that has a Bootstrap class of alert, and let's qualify that with alert-info, so it's an informational alert,
and inside of that div we will place TempData sub Message. And now if I save my Layout view, and in fact I want to rebuild the
entire application, I'm going to Shift+Ctrl+B, I can now come back to my application. I want to go and edit Scott's Pizza 3.
When this comes up, we will make this the fourth iteration of the restaurant and click Save, and now I can see my message appears
that I have saved the restaurant. But if I come back to this page, which is the details for Scott's Pizza 4, that message is going to be
gone because that entry, that message entry, it's going to be removed from TempData after that request. So I can edit this restaurant
as many times as I want, and that message will be in place including the semicolon, which I always have a habit of doing
this, placing a semicolon at the end of every C# expression, but obviously that's not needed inside of Razor where you just write the
expression and the semicolon is not required. And the next time I refresh this page or go to the details for Scott's Pizza 4, that
message about saving the restaurant will disappear. So now you knowabout TempData, as well as ViewBag, two different data
structures with two different purposes. TempData is really about passing data between controller actions, so across requests,
whereas the ViewBag is really about passing data between different views that are used in the same request, so between, for
example, my content view and the layout view. And we've also seen how to utilize partial views and how to have content views
render into different sections on a layout view. In the next module, we're going to continue with this UI theme and talk about some
of the other work that we can perform on the client using ASP.NET MVC and its associated technologies.

Front End Frameworks


Managing Client Libraries
Hi, this is Scott. And in this module, we're going to see how to perform some work on the client side in the browser with ASP.NET
MVC and Visual Studio. I want to show you how to manage your client-side libraries like jQuery and Bootstrap. We'll also talk
about bundling these client-sideassets to get those files to your customers as quickly as possible. And we're going to see how to
enable and configure client-side validation in theapplication. I will also walk you through the single-page application
template provided by ASP.NET MVC. But before we can build a single-page application, we need to learn a bit more about how to
manage client-side libraries. Over in Visual Studio, when we created our application, there were already a number of client-
side libraries preinstalled into this project template. Let's open up the Scripts folder and take a look. It's inside of here where I can
see, we're already using jQuery, and there's several different distributions of jQuery here. Generally, a JavaScript file with a .min in
the name, min, means this file has been minified. So it's been crunched down to be as small as possible. When you run JavaScript
code through aminifier, the minifier's going to remove all the whitespace and even rename local variables so that the variable names
are as short as possible. And that's why jQuery, this file, if we browse through the source code, it's somewhat readable. There's a lot
of source code here, but it is readable, there's whitespace, there's formatting. If we open up the minified version of jQuery, this file is
going to be very difficult to read. Because first of all, all of the unneeded whitespace characters have been removed, so we
don't even have line breaks, but on the other hand if we send this file down to the client, it's going to be a lot smaller. So it's going to
get processed a lot quicker. So we have several versions or distributions of jQuery. We're also using jquery-validation, that's
already installed, that's a plug-in for jQuery that enables some client-side validation features which we're going to take advantage of
here in this module. There's also Bootstrap, which consists of a CSS file because Bootstrap is a CSS framework, but Bootstrap does
come with some interactive components like a picture carousel that will keep rotating pictures through a page, and those
interactivecomponents require JavaScript. Therefore, we have bootstrap.js and bootstrap.minify .js in the Scripts folder. And
then there's also a library called Modernizr. If you support customers who are using some of the older browsers out there
like Internet Explorer 9, or even Internet Explorer 6, then Modernizr is a JavaScript library you want to look at and take advantage
of. The goal of Modernizr is to modernize those older browsers, so addsome features into those browsers using JavaScript that
otherwise would not be supported. If you do a search for Modernizr on the internet, I'm sure you will find the documentation that
you need to take advantage of that library. But now the question you might have is, how do I manage these libraries? What if there
is a newer version of jQuery that I want to take advantage of? Well with ASP.NET MVC and Visual Studio in general, there's
been a few different approaches that you can use to manage client-side libraries like Bootstrap and jQuery and Modernizr.
One approach is to simply go out to the official sites for these particular frameworks and click on a download button to download
and then manually copy thesefiles into the Scripts folder, or perhaps into your content folder, that's where we will find the Bootstrap
CSS files. So you download and then copy the files that you need into the project. That's one possible approach. Another approach
that we've used in the past with ASP.NET is to manageclient-side libraries through NuGet packages. So if I go in and say I went
to manage NuGet packages, I can do a search for something like jQuery, and I will find that I do have the ability to install a jQuery
package, and this will place the JavaScript files that I need into my project. This is another viable approach for you, but I will say
that over the last couple years, there's been a shift away from using NuGet for client-side assets, like cascading style sheets and
JavaScript files. Instead, we've been trying to restrict NuGet to just working with .NET assets. So how do I obtain a library or
a framework like the Entity Framework? Well, I can install that piece of software as a NuGet package. How do I obtain
something like jQuery or Bootstrap or Angular? Well, for these client-side assets, perhaps I should use something that's been
optimized for that client-side environment, because NuGet was really optimized for .NET. So what can you use for client-side
package management? Well there is npm, the toolthat is associated with Node.js, the Node Package Manager. I'm not going to show
you how do that in this course, I do show you how to do that in my ASP.NET Core course. Npm is a relatively simple tool, but
if you'd like to just stick with using Visual Studio, there is a way to manage theseclient-side assets officially through Visual Studio.
So if I right-click on OdeToFood.Web and say that I want to Manage Client-Side Libraries, or evenbetter, if I click and say that I
want to Add, and then select Client-Side Library, Visual Studio now has the capability to go out and search and download client-
side libraries and frameworks that I want. So for example, if I wanted to look for jQuery because I didn't have it in this project
already, or I wanted to update to the latest version, then Visual Studio can go out and say, hey, I found jQuery version 3.4 .1. It's on
a provider named cdnjs, and you can see there's several different providers here that Visual Studio can use to download a
particular library. And I can also select specific files that I want to download. So if I just want to download jQuery and not
the minified version, or I want to download just the minified version, I can do that, but we can include all library files. I can also
specify different version numbers here. And once I click Install, VisualStudio will not only download all of the files that I specified
and place them into the lib folder, it will also maintain a record of what has been installed. So if we look through this project, we
will find there is a new file here, which is Library Manager .json, libman.json. This file describes to Visual Studio what I
have installed, so I have the library jQuery version 3.4 .1 installed from cdnjs. Whenever you update or download this particular
library, place it into the lib/jquery folder. So now moving forward, what I can do when I check this project in the source control, I
just need to makesure that libman.json is checked into source control. I don't necessarily need to check in the lib folder because
Visual Studio can recreate that folder using the information that is in this JSON file, just like I don't need to keep around NuGet
packages if I have a packages.config file that tells Visual Studio what packages I have installed. And now in the future, if I see
there's a new version of jQuery that is available, let's say version 3.5, and I want to test out that version to see if everything is
still compatible and working, I can simply change the version number in here, save this file, have Visual Studio go out and fetch
those new files, download them into the Lib folder, and I'm off and running with this new version of jQuery. Now for this course,
I'm not going to be using the Visual Studio Library Manager. We're just going to continue on using the scripts and content that were
already installed by the project template when we created this application, just to keep things simple. But now you know about an
approach that you can use to manage your own client-side libraries in your own application.

Bundling Client Assets


The template we use to set up our MVC application also set up bundling for client-side assets. Now I do want to preface the
following discussion by saying that if you're living in a world where your clients and your server are mostly using the HTTP/2
protocol, bundling of client-side assets is not as important as it was in the days of HTTP/ 1.1 and 1.0. So, IIS in Windows Server
2016 and later supports version 2 of the HTTP protocol, which has optimizations to make the downloading of client-side assets,
like JavaScript files and cascading style sheets, a lot more efficient. This project is really set up for those clients or those servers that
don't support HTTP/2 because what it tries to do is bundle as many script files together as it can into a single download. In the past
that was more efficient than having, let's say, five script files that the browser had to download, all five, we bundle them together
into a single download and also minify that file to make the download as small and as efficient as possible. It's not so much of a
concern with HTTP/2 these days, but if we go into the Views folder into the Layout view, you'll see that we have these HTML
helpers, Styles and Scripts, which allow us to render the HTML elements that instruct the browser to download JavaScript files or to
download cascading style sheets. We can see that when we run the application and look at the source code for the page that
is produced, let me right-click and actually do an inspect element because I should see if I scroll back up to the top of the page,
inside of the head element, that we have a link to bootstrap.css, we have a link to site.css, which is the CSS file specific to the site,
so Bootstrap is a library, site.css is the file that we would modify to add custom styles to our application, and then there's a link
to Modernizr. You typically want to load that at the top of the page, even though most JavaScript files, you want to load them at the
bottom of the page or as late as possible. Modernizr is one of those libraries, if you take advantage of it, you want to load it as early
in the page as possible, but down here at the bottom of the page we can see we render scripts for jQuery and Bootstrap, and again
coming back to the layout page if I scroll down, those scripts files were rendered because I have Sripts.Render, and you can see
wewant to render the bundle called jQuery. So what this is rendering are abstractions around our JavaScript files and our CSS files
known as bundles. These bundles get configured, so if I look in BundleConfig.cs, I should find where the Bootstrap bundle is
configured and where the jQuery bundle is configured. So let's open up BundleConfig and I can see jQuery is a ScriptBundle that
will include some version of jQuery. So this is telling thatMVC framework, go into the Scripts folder and look for jquery- and some
version number. So it could be 3.3 .1, which is what we currently have, or it could be 3.3 .2. Essentially, this is trying to be
very flexible as we move forward in the future and update our library. So if I drop a new version of jQuery into this folder,
this software is smart enough to say, oh, you must want the latest version, which is 3.3 .2, so I'm going to pick that up and put it into
a bundle. These bundles can also detect if you're running in debug mode or release mode, and when you're running in release mode,
that should be when you're in production. These bundles will make sure the files are minified and squished together, concatenated
together. Right now we just have one bundle for jquery and one bundle for jqueryval. A lot of people would take all those script
files for both jQuery and the validation plugin and put them together into a single download, and then when I do a scripts.render on
jQuery, the resulting file that comes into the browser would include both the jQuery library and jquery-validation. And in this API,
you can see that there is a params argument to the include method, which means I can keep including as many strings here that point
to as many files as I want. So I could go out and include jQueryand the validation plugin and Bootstrap altogether into a single
bundle, and then when I do a scripts.render on the bundle name, which is specified here, that would download the bundle of files
that has been put together by the script bundler. We can also see there is a bundle for Bootstrapand there's a bundle that
includes bootstrap.css and our custom style sheet, site.css. So that's a good example of where I place two files into a single bundle,
it's just when I run in debug mode, the style bundler assumes I want to make things easy for debugging, so it doesn't actually
concatenate files together. When I say in the Layout view that I want to render Content/css, what Styles.Render will do is say, oh,
inside of Content/css, you wanted these two CSS files, let me render individual link tags for those to make things a little easier for
debugging. But if we switch over into production mode, which I'll show you the important setting and where to do that
in Web.config in the next module when we talkabout deployment, when we switch over into release mode, there will be a single
link tag emitted that points to a virtual file, you can think of it, that includes the contents of both bootstrap.css and site.css, that's
efficient for the browser, especially if you're not using HTTP/2. And now that we've covered bundling, let's dig into what jquery-
validation provides.

Enforcing Client Validation


Inside the application earlier in the course we saw where we do have validation for creating and editing restaurants. So whenever we
manipulate restaurant data, it's not legal to do something like have a restaurant that has no name. If I try to click Save, I'll see that the
Name field is required, and actually there's a bit of a bug here in that I display the same validation error twice. Let's fix that really
quick. If I come into the Edit Razor view, I'm pretty sure I know what this is. It's because I copy and pasted earlier in the course,
which always, always, always leads to problems, but Icopied and pasted all the markup to input the restaurant name and then pasted
it and just modified Name to Cuisine, only I forgot that here in one location, which is the HTML helper that displays a
validation message for. So we have validation, but this validation happens server side. In other words, when I click Save we have
to send a request all the way to the server, process that request, find that the restaurant name is null or empty, and then send error
messages back down to the browser. That's okay in many scenarios, but there's also some frameworks that make it very easy to do
common validations on the client side. So something like having a required field is something I can implement using JavaScript on
the clientto make it fast and efficient. So as soon as I start typing here, that validation message should go away because
obviously I'm providing a name, and if I don't have a name and I click a button to post this form back to the server, the
JavaScript can step in and prevent that post from going all the way back to the server, it can immediately display these
validation error messages. And actually, ASP.NET MVC has everything set up to provide support for client-side validation. We're
just missing one piece, which I'm going to show you in the next clip, but for right now I just want to right-click on this input, say
that I went to Inspect Element, and you'll notice we do have an input, an input whose type equals text. But notice all these attributes
that start with data-, so there's data-val = true, or data-val. There's data-val-maxlength, which seems to include the error
message.But what happens if I've exceeded the maximum length for a restaurant name, notice there's the maxlength value,
255 characters. There's data-val-required, essentially saying this field is required and here's the error message to display if this field
is not populated. So all the metadata or client-side validation is in place, and where does that metadata come from? It comes from
the HTML helpers. So what I say please give me an editor forthe model name, the editor for HTML helper can look at my model
class, which is a type of restaurant, and look at some of the data annotations that we have in place, like required and maxlength. It
can then take the parameters for those types of validations and encode them into these data- attributes, and then all we need is some
JavaScript that can work with those data- attributes. And that is the role of some of the validation libraries we have in here,
specifically jquery.validate, which is a plugin for jQuery to support client-side validation, and jquery.validate .unobtrusive is a
jQuery plugin provided by Microsoft to act as a bridge between these data- attributes and the jquery-validate plugin. So it's going to
make the magic happen. So if I have jquery and jqery.validate and jquery.validate .unobtrusive, all those scripts loaded onto our
page, I should have client-side validation automatically. Let's look at how to enable that.

Enabling Client Validation


Currently in the application, the edit a restaurant and create a restaurant features do not support client-side validation. And there's a
simpleexplanation for that. When I created those features, I would add a view using the scaffolding tools in Visual Studio, so
I would right-click a folder and say that I want to add a new view. And I would select a template, like the Edit template or
the Create template, and I would select my model class, and then I would leave unchecked this checkbox to reference script
libraries. It is this checkbox that will insert additional scripts into thatparticular Razor view so that the client-side validation will
work, and this will tie together a few things that we've been learning about. Let's go ahead and create an edit view just named View.
I'm only doing this temporarily, we're going to throw this view away, but I do want to select this checkbox and show you that there's
really only one significant difference between this view that I just scaffolded and the other views that we'reusing for create and edit.
And that difference is these additional three lines of code at the bottom of the view. This is defining a section named Scripts. So
you might remember from the last module when we talked about sections in a layout page. If I come over into our layout page,
I will see down here at the very bottom of the page, the layout page tells the framework to render a section named scripts. It is an
optional section, so notevery view needs this section defined, but if it does exist, like it does on our new view, that section will allow
us to render script tags down here at the bottom of the page after jQuery has been loaded and after Bootstrap. And it's important,
if you're using a jQuery plugin to load scripts in the proper order. So first I have to have a script tag that downloads jQuery and
defines the jQuery object, and then I can load the plugins and then I can load the plugins that depend on the plugins. So that's
essentially what's happening with client-side validation. Load jQuery first, then loadjquery-validate, and then load jquery.validate
.unobtrusive that builds on top of those two previous libraries, and that's what RenderSection will allow us do, specifically we're
going to render anything that was bundled into jqueryval. And so, tying things together from some of the things we've seen
throughout this course, if we go back to BundleConfig, you'll notice the jqueryval bundle includes jquery.validate *, which
allows us to pick up not only jquery.validate .js, but also jquery.validate .unobtrusive .js, and yes, again, the script bundler has some
heuristics and is smart enough to detect the jquery.validate .min .js is just a minified form of jquery.validate .js. So it doesn't need to
include both of those files. It's probably just going to take .validate .js and run its own minifier and then concatenate that together
with jquery.validate .unobtrusive when we are in release mode. And that is how ultimately we can support client-side validation.
Simply by making sure that we render that jQuery validation bundle. So let me take this section of scripts, I'm going to copy it, then
I'm going to delete this view that we just created temporarily. So delete the View, View, and inside of edit.cshtml, I'm just going
to scroll to the bottom and paste in the call to Scripts.Render. We can also use this in the create view, so if I scroll down to the
bottom I will paste that in here too. Let's save all the files, let's do a build in the project just to make sureeverything is starting from
scratch, let's come back and let's issue a Get request for /restaurant/edit/1, and I can now try to blank out the name of my restaurant
and click Save, and what we'll discover is that a request didn't reach the server that time. In this case, JavaScript was able to jump in
and prevent that request from going to the server because the JavaScript has already detected there's going to be a validation error.
And then as soon as I start typing, you'll notice that validation error message goes away, as soon as I remove that text the validation
error message reappears. So that's the jquery-validate plugin operating with each keystroke to validate what is inside of this form. So
all of your common validations, the length validations, the required validations, regular expressions, the range of numbers, all those
simple types of validations are supportive through data annotations in C# code, and also this client-side validation framework. If
you have more complex validations, a lot of people ask me thisquestion, how do I enforce complex validations, particularly business
type domain-oriented validation? Like VIP customers get to have this amount of discount, but only when the day is Thursday, those
sorts of complex logical validations. Many times I tell people don't worry about trying to enforce them on the client side, but make
sure you always enforce all of your validations on the server side. So even though we have client-side validation in place in
this application, we still need to check model state and verify that we have valid models before we take any action on the server side
because it's very easy for people to circumvent client-side validation. So client-side validation provides a more interactive
application. It can be a little bit quicker to respond for the user. But what if you want to go one step further and build a single-
page application? Well, let's build one using a template inside of Visual Studio, and I'll give you an overview of what is happening
inside.

Creating Single Page Apps


What I want to do in a new instance of Visual Studio is create a new project, so unrelated to the project we've been working on, it's
going to be a brand-new application, and it's still going to be a web application, but I want to use a different template when I create
this application. So I still want a C# project that will run on Windows. So in other words, the .NET Framework, and I still want to
select this option to build an ASP.NET Web Application on the .NET Framework, let's click Next to move forward. I'll just leave
the name as WebApplication2, the important part is here on this next screen where instead of selecting the MVC template, I want
to select the option to build a single-page application. We're just going to createthis application quickly, and I'll show you a few
features that are inside. It's going to take Visual Studio a moment to scaffold out this application. And what we're going to have is an
application that's going to be a little bit different than the application we previously scaffolded at the beginning of this course. This
application is going to include a framework to manage user identities. In this application, when I run it with Ctrl+F5 to run without
the debugger, should immediately force me to register or log in. So this opened a web browser on a different monitor, let me drag
this over here where you can see it. We will once again go through this dialog that tells us we're working with a self-signed
certificate, are we sure wewant to do this? I will say yes, accept this risk and continue onward. And when we enter the application,
I'm immediately asked to log in, and that's because even the home page of this application requires an authenticated user. So when
ASP.NET sees I'm an anonymous user, it brings me to the login page. Since I do not have a login, I will need to register as a
new user. Let me go ahead and fill in some details. So this is my email address, I'lljust put down a hometown of Baltimore.
I'm going to use my password manager to generate a password. This password includes uppercase, lowercase, digits, and symbols.
That seems pretty good, so let's fill the password. I will update my password for localhost, and let's register for this application, and
I am now logged in as scott@ odetocode.com. Perfect. I can see my home page has now personalized, my hometown is Baltimore,
and I can come over to this API page. It shows me some documentation about an API that is available in this
application, specifically there's an API at /api/Me that will return my hometown. So this is where we were talking about the web
API. The web API works really well with single-page applications because typically what you're going to be doing in your single-
page application is not retrieving HTML from the server. You're not going to be rendering Razor views, instead you're typically
going to have some JavaScript on the client, whether it's jQuery or Angular or Knockout JS or some other framework or library that
you're using, and that JavaScript is going to make HTTP calls to your API controllers to get information, or to post, or put, or delete
information. And what we'll find on this home page is that most of this HTML is rendered just as static HTML, but this little bit
that appears here, Baltimore, that's placed here through what we used to call an AJAX call. So we're using JavaScript to call back to
the server, to call back to an API controller to say, who is this user and what is their hometown? So let's look inside the project just a
bit. The first thing I want to point out is that we still have a collection of controllers, and now most of these controllers are
the traditional controllers that we've been working with in our application, so controllers that derive from the System.Web .Mcv
based controller class. So here's our HomeController, here's our ManageController. This is the controller that allows me to manage
my profile, which I can do if I come and click on my username up here, scott@ odetocode.com, I can change my password. But
there's also in this application the MeController. So this controller doesn't necessarily have to be in an API folder, but you'll notice it
is an API controller. And so it's a controller that I should be able to invoke from JavaScript, and it can return to me information
that's either in XML or JSON format. So we'll notice if we scroll down here, if I issue a GET request to /api/Me, this controller will
use a component from the Identity framework, known as the UserManager the find the current user that will look me up in the
database. So all that information is stored in the database and it's stored securely, so passwords are not in plain text, but this action
willreturn a view model that includes my hometown, and that can be then placed into the screen. What does that look like from the
client side? Well, let's look at the index view for the home page, and what we're going to see is that all this index view, all it really
does is, first of all, render a partial view named _Home, which will contain the HTML markup that we need for our home page, and
then it's going to render some scripts. First it's going to render a bundle for Knockout, then it's going to render a bundle for the app.
If you want to dig into exactly what is inside of those bundles, then you now know that you can look in the BundleConfig. What
you're going to find is that Knockout is a JavaScript framework that offers client-side data binding and change detection. So it
makes building a single-page application easier than just using something like jQuery or raw JavaScript, and then we also have a
bundle for our application. What we're going to see if we look in the Scripts folder is that there is an app folder, and this app bundle
is basically going to include those files that are in the app folder. So this isn't a course on jQuery or JavaScriptprogramming or
Knockout JS. You'll find those courses on Pluralsight. I just want to point out that the core logic of this home page will be here
inside of home.viewmodel .js. The real core behavior of this application happens right inside of here, but essentially when
the application loads up, we're going to use jQuery AJAX features to make an HTTP GET request to the userInfoUrl, which
is /api/Me. We're also going to be passing along a Bearer Authorization header, which will identify the current user to the API. So
that's simply an HTTP header that is Authorization : Bearer, and then an access token that's been granted by the Identity system.
And when that API call returns successfully, it's going to return some data, and we're going to update in the DOM on the page, the
text that displays Your Hometown is, and then place the data on the page. And ultimately what that will render is what we see here,
Your Hometown is Baltimore. So that's a quick overview of the single-page application template that Visual Studio provides. Of
course these days you might be building sophisticated single-page applications using Angular or Vue.js or React, and ASP.NET and
ASP.NET MVC will support those frameworks also, and you can use a lot of the features and technologies that we've covered in
this course to build those applications. And for all those types of applications, your API controllers become more important than
your MVC controllers because typically in single-page applications you're going to be making calls to the server, your server is
going to return data to your client-side application in JSON format, and then you're going to use your particular client-side
framework, be it Angular or Vue or Knockout JS, to place that data onto the page of the appropriate location.
Deploying ASP.NET MVC Applications
Evaluating the Deployment Options
Hi, this is Scott. And in this module, we're going to look at how to deploy our ASP.NET MVC application. So we're going to learn
about all those little details that we need to know in order to take our application from running locally on our machine in
development to a real web server, perhaps directly to a production server or maybe a test and QA server first. And like everything in
software, there are different approaches that you can take to deploying ASP.NET. I'm just going to show you one approach
using Visual Studio, but if you work for an organization or a larger team, your company might already have a build and deployment
process set up for you, perhaps using a tool like Azure DevOps. If you are curious how Azure DevOps works, that's a topic I cover
in my Azure for .NET Developers course. In this module, in this course, we're going to use Visual Studio, and even with Visual
Studio, I have options on how and where I deploy my application. One option with Visual Studio is to publish our application to
IIS directly, IIS being Internet Information Services. This is the web server for Microsoft Windows and Microsoft Windows Server.
And in development with Visual Studio, we've been using a lightweight version of IIS known as IIS Express. In this module, we
will use the full version of IIS that I have installed on my machine, but I do want to point out that this technique works with both
local and remote machines. So as long as I have the right permissions and credentials, I can use Visual Studio to publish to
IIS running on a machine somewhere else on my network, and I can also publish my app to, let's say, a virtual machine running
in the cloud. Again, all we need is permissions and connectivity so Visual Studio can talk to the right components on other
machines over the network. Another option for publishing is to publish to an Azure App Service. App Services are a great managed
platform for hosting web apps and web APIs. If you're interested in using App Services, my Getting Started with Azure course can
walk you through everything that you need to know. And yet, a third option is to use Visual Studio to publish the application to a
file system. This option gives me a folder on the file system with all the files that I need to deploy into production. So, with
these files I can create an archive, a zip file, and I can copy these files to a network share for someone else, like some administrator
to take and deploy to production. There's a lot of flexibility here because you'll have all the files that you need in one place and then
you or someone else can move them into a server in a location for IIS, and you can use other tools and other people in
your organization to do that. And this is actually the approach I want to show you.I'm going to publish to the file system and then
show you how to point IIS to that location on the file system. And if you want to follow along, you are going to need to make sure
that you have the right software installed. So let's look at that next.

Installing Web Server Software


Two pieces of software that you'll need to have installed to follow along. The first is a new version of SQL Server. Why is that?
Well, we did see in this course how easy it is to use Microsoft SQL Server, the LocalDB version. LocalDB is a version of SQL
Server that gets installed by Visual Studio and it's very easy to use in development. Unfortunately, when it comes to running a real
web application in production in a real web server like IIS,there's some difficulties getting LocalDB and IIS to work together
because ISS, being a real web server, runs as a Windows service in a privileged context, whereas LocalDB, being a development
database, is a process that runs with my credentials and not as a service. And the two are justgoing to have trouble communicating.
Yes, you will find some blog posts and articles on how to get SQL Server LocalDB and IIS to work together, but I've taken what
I think is a simpler and easier approach, and that is to install a version of SQL Server that will work well and easily with IIS. It is
still a free version of SQL Server. So if you do a search for SQL Server download, you should be able to come to the SQL Server
downloads page. And if you scroll down, you will find a free specialized edition of SQL Server. In fact, there's two different
editions that are free. The first, the one I have installed already on this machine, is SQL Server Developer. SQL Server
Developer comes with all the features of SQL Server. It's just not licensed for production use. But as long as you're using this
edition of SQL Server for testing and development, then you'll be just fine, and this is what I have installed. And because this
version of SQL Server runs as a service in a privileged context, much like IIS does, the two have an easier time
communicating together. Another option, if you want a slightly lighter weight version of SQL Server, is to download and install
SQL Server Express. In fact, LocalDB is simply a lighter weight version of SQL Server Express. The difference being that
LocalDB only works for me, the developer, whereas SQL Server Express, it still works as a service and it's something that you
can use even in production as long as you have a small dataset. So it does have restrictions on how large a database can grow. Once
you have one of these SQL Server editions installed, you should be able to come into Visual Studio and reach your new instance of
SQL Server. So for example, I already have SQL Server Developer Edition installed. So let me go to the View menu and I want to
go again to the SQL Server Object Explorer. It is here where we established a connection toMSSQLLocalDB, and that allowed us to
see that we were in fact creating our OdeToFoodMVC database inside of this SQL Server instance, but now I want to connect to a
different instance of SQL Server that is running on my local machine, and it is not SQL Server LocalDB. It's SQL Server. It's going
to be the Developer Edition, but to a client like Visual Studio there's no obvious difference between Developer Edition and Full
Edition. So what I want to do is right-click on SQL Server, say that I want to add another server that is out there somewhere. I know
this one just happens to be on my local machine. So I'm going to select the name of my machine here, which is DESKTOP-
55DA34R. You could also put in a dot here. That always tells the SQL Server connectivity tools I want to connect to this machine
that I'm already on. And yes, we're going to use the default authentication, which is going to be to use my Windows identity,
and because I am an administrator on this machine I should be able to connect tothis database, which I did. And if I expand this out,
I can see there are currently no databases, but ultimately by the end of this module, I want to see the OdeToFood database as a
database on this SQL Server instance and I want to have my application running in IIS and pointed to this SQL Server instance, not
the LocalDB instance. So in addition to SQL Server, you're also going to need IIS installed. So yes, typically in a real production
web server you'll have IIS installed on Windows Server. I'm not using Windows Server here for this machine, I'm using Windows
10 Professional. But you can install IIS on versions of Windows other than Windows Server. You just have to be very careful about
the production licenses and how many concurrent connections are allowed. But for test and development you can certainly install
IIS into Windows almost any edition. So I want to make sure that I have IIS installed on my machine. That's not going to be there
by default. The easiest way to do that is to go to the Start menu. And I'm going to type for features, do a search for features
because the Control Panel component that I want to run is this one that allows me to turn Windows features on or off. I'm going
to click to select that. This is where I can enable Windows features, like Containers. Do I want to work with Windows
Containers? Do I want to work with Virtualization with Hyper-V? And also, do I want Internet Information Services, the web
server?You'll want to make sure that you check this box and make sure you have at least the IIS Management Console selected.
Now inside of World Wide Web Services, there's a few features that we need to make sure are enabled. You'll want to make sure
that the features for Static Content, HTTPErrors, Directory Browsing, and Default Document are enabled. That's going to make life
easier with IIS. And I also want to make sure some of my application development features are enabled. I want to make sure, for
example, that .NET Extensibility 4.8 is enabled, ASP.NET 4.8 is enabled. That's going to select a couple additional features by
default that I'll need. What I don't need is the feature that allows me to run Classic ASP. I don't need the CGI feature. I don't
need Server-Side Includes. But I do really need all the features that will allow me to host an ASP.NET application. And once those
features are selected, I'm going to press OK. Windows will spend some time downloading and installing various components. When
this is done, it might require a reboot, but at the end of the process I should have everything I need to run my ASP.NET application
under IIS. Here we are just after Windows has finished installing my new features and I've rebooted. I should now be able to open
up the Start menu and search for IIS. What I want to look for is the IIS Manager. I want to open this application. It opens on a
different monitor, so let me drag it over here to the screen where I am recording. And it is this application that allows me to manage
the applications and services that are hosted on my machine. So if I expand to open Sites, I can see there's a single site currently that
is hosted on my machine. So IIS can manage multiple applications and multiple services on a single machine. So I can host, let's
say, 10 or 20 applications on this machine. It really depends on how large those applications are and how much CPU and memory I
have on this machine, but this default web site that comes by default, it's going to be hosted on HTTP and on port 80. I can click
here to browse that website. That will open up a browser that takes me to localhost, so no port number. We're going directly to port
80. And what I'm seeing is the default website that is managed by Internet Information Services. Our goal is to build out andpublish
OdeToFood. And when I come to look on host port 80, I will be looking at my application, OdeToFood. That's the point we want to
get to.
Publishing Apps with Visual Studio
As I mentioned earlier, there's many different ways to publish a web application. We're going to use the Visual Studio approach. An
alternative would be to use the tools that Visual Studio is using behind the scenes. So these are command line tools like MSBuild
and Web Deploy. Using those command line tools allows you to automate this publishing process, and that's what you need to
do when you start working on a larger team or at a larger organization. I'm going to show you the Visual Studio approach. The way
to do this in Visual Studio is to right-click on a web project and select the Publish option. The first thing I'll need to do is select my
publish target. So my publish target could be an App Service that is inside of Microsoft Azure. I can create a new App Service here
if I want to or select an existing App Service after I log in. I can also publish to a virtualmachine that is inside of Azure. Again, all I
need to do is browse to that virtual machine that I have created. And another option is to publish to IIS, using either Web Deploy or
File Transfer. So again, Web Deploy is a component of IIS. It's also a command line tool that I can use to publish an application.
And you can think of Web Deploy as being the native tool that is used to publish into IIS. But not every scenario and not every
environment is going to support Web Deploy, so another option is to use FTP, or File Transfer Protocol, because ultimately
publishing a web application is all about copying all the needed files to the web server. And so in some scenarios, perhaps with
older servers, all you really need is an FTP connection to move everything that you need from this computer to the web server. The
approach that I'm going to show you is how to just publish to a folder because in a way if I publish to IIS, that's just too easy. I just
tell Visual Studio publish to this IIS server, click on a few buttons, and it's finished. What I'm going to do is publish to a folder.
Inside of that folder then will be all the files that I need to run my application. And then I'll show you how to manually configure IIS
to create a new website and point that website to my application. That will give you an idea of what's really happening behind the
scenes when I do a full publish to IIS inside of Visual Studio. It also really gives you an idea of what's happening, the
abstraction behind an Azure App Service because if you select Azure App Service and use a Windows-based app service, that's
really a platform where Azure manages IIS for you. But we're going to use this folder approach. So the first thing I have to do is
choose the folder where I want to publish all the files for my application. By default, I will have a folder that is inside of where this
project exists, but inside of the bin\Release\Publish folder I'm going to select something different just to get it out of my source
code directory. So I'm going to browse and I'mgoing to select a folder that I've already created on my C drive called web, but
then I'm going to create a folder inside of there. And let's just call it OdeToFood. And that will be my destination.
So C:\web\OdeToFood. You can select any folder that you like. And then I'm going to click Publish. Visual Studio is going to go
off and do a build and then also a publish operation, and this should finish very quickly because this is not a largeapplication.
There's not a lot to build and to copy around. And I can see down here in the output that I did succeed with my publish operation. I
just want to point out that with this publish operation, we did a build in what we call release mode. That is by default when I created
this webapplication, which is really a C# development project, there were two configurations given to me. There was the debug
configuration and the release configuration. So far in this course, we've just left this at the default, which is to build and execute
using a debug version of the application. When we publish this application, presumably we're taking it somewhere into production,
so we want the configuration to be release mode. And there's a number of small differences there. For example, the C# compiler
is going to run with more optimization. Well for the most part, I should be able to open this folder. And I can do that just by clicking
on that. And inside of this folder I will find all of the files that I need to run my application. So that includes files like in the bin
folder, all the assemblies that I need to execute my applications, so all of the DLL files, including OdeToFood.Web .dll
and OdeToFood.Data .dll. I will also find inside of the Views folder my Razor views. So here inside of the Restaurants folder,there's
index.cshtml, which is essentially the home page of my application. What will I not find in the published output? Well if you look
through these folders, you will not find a Controllers folder. So there is no C# source code that is going to be included in the
published output because of all the C# source code has been compiled into an assembly. So OdeToFood.Web .dll or
OdeToFood.Data .dll. So those files are not needed, but myWeb.config file is needed, that's the configuration for my application.
My Views are needed. Any script files, any content that I have. So static assets, like bootstrap.css, all of that is placed into this
folder, and I now have a folder that I can run my application from.

Creating an IIS Website


Now that we have a release build of our application and all the files that we need published into a single location, let's take a look at
setting up a new IIS website that will point to the application at this location. So let me come back to the ISS Manager, which we
opened up earlier. And what I want to do is create a new website. It's also possible that you could add your application as a
directory under the existing website, the defaultwebsite, but I'm going to show you how to set up a brand-new website. Now if I
want OdeToFood to respond to a request to this machine on port 80, then I'm going to need to do some reconfiguration because
IIS already has a website configured to run on port 80, and that is the default website. If I right-click on this default website and go
to Edit Bindings, what we'll find is that every website we add to this machine, because IIS on this machine can host multiple
websites, it can host dozens of websites if they're small enough, but every website needs a unique binding thatallows IIS to
determine where to send an incoming request. If I have 10 different websites configured and running on this machine under IIS and
an HTTP request arrives, how does IIS know which of those 10 applications to send this request to? It's going to know because
every website is going to need a unique binding. Every binding consists of a host name, a port, and an IP address. So if I have
10 different applications on this machine, Imight differentiate them by having this machine reachable across 10 different
IP addresses, and then I send a request for each of those 10 IP addresses to a dedicated application for that IP address. I could also
host name. So if I set up the right DNS entries, I can reach this machine as OdeTofood.com, and OdeTofood.net, and
OdeTofood.org, so three different host names for this one machine, but I can also use the host name to tell IIS which website to
route a particular request to. So this is almost like a form of routing that happens at the server level before we even get into
our application and we route to a specific controller. But by far the easiest way to route, because I don't have to make any DNS
changes, I don't have to make any networking changes, is just to route by port number. So if a request arrives at this machine for
port 80, any host name, any IP address, that request is going to go to the default website, but if I want that request to go to my new
OdeToFood application instead, I'm not going to be allowed to add two websites that both take messages over the same port without
having a different IP address or different host name. And since I'm not going to change the host name or the IP addresses, I'm going
to need to change the port that the default website is listening on. I could also delete the default website. I could also replace the
default website with OdeToFood. But I'm going to take this approach of just changing the port for the default website. So I'm not
going to do anything destructive and you don't have to do anything destructive on your machine. I'm just going to say that I want
to change the port to port 81, select OK, and now if I come back into my browser, this website that used to respond to localhost port
80, if I do a hard refresh on this website, that website no longer exists. So I am unable to connect. However, if I go to port 81 and
press Enter, I have now moved that default website over to port 81. And now what I want to do is set up a new website that points to
my OdeToFood application. So back in the IIS Manager, one way to add a website through this UI is to right-click, say that I want
to Add Website, and I can first give this site a friendly name. Let's just call this OdeToFood so it's very obvious when I'm looking at
my list of sites which one isOdeToFood. And then I specify a content directory. So I need to tell IIS where are all the files for this
application. And all these files are going to live in that folder that we just created with the Visual Studio publish operation. So
keep in mind if I use Visual Studio and I publish directly to IIS, these are some of the steps that Visual Studio will take care of for
me, but I wanted you to see these steps explicitly because it can help when you need to troubleshoot to understand what actually
happened behind the scenes. So I'm going to configure the physical path to go to that web folder that we created, and select the
OdeToFood folder that is inside of that web folder and select OK. And at this point, IIS is smart enough to understand ASP.NET.
It's smart enough to understand, oh, there's a bin folder in this location where I can load up assemblies for ASP.NET, and
itunderstands it's going to be running that web application. We're going to have it start immediately. We're not going to change any
of the binding information. So again, if I already had a website on port 80, I would either need to change the IP address that this
website responds to or change and provide a host name, or change the type. So I could bind HTTP to one website and HTTPS to
another one, but we're just going to use regular HTTP traffic. And before I press OK, I just want to point out that IIS is going
to create a new application pool for my application. This application pool name is going to be OdeToFood. What is an application
pool? An application pool is the actual process that is going to be executing on this computer that will host the code that is executing
for my application. So what IIS can do is put various websites into different application pools so they're somewhat isolated into
different processes. That way if my application pool crashes for some reason, OdeToFood crashes, I don't bring down any of the
other application pools that might be running the other websites on this machine. Another important reason to understand
whatapplication pool you're a part of is if you need to know the identity that your web application is going to be using. So when
your web application accesses files on this computer or accesses resources on this computer, or goes to access let's say a database,
what is the inherent identity that the application is going to have? The identity it's going to have is the same as the application pool.
And we'll see why this becomes important when I need my application to access a SQL Server database. But for right now I'm just
going to say, yes, let's create this new website. So I can now see OdeToFood in the list over here. And I should be able to come
back to my web browser. And instead of going to port 81, which is the default website, let's go back to port 80, which is where
OdeToFood lives. But I'm going to run into a bit of a problem. Eventually, I should see an error for my application. It just might
take a little bit of time, but eventually my application is going to figure out that it cannot reach the database that I need. So, the home
page of the application is going to try and get a count of the number of restaurants that are in the application. With the database my
application is configured to use, which is LocalDB, it is not going to be accessible for my application when it's running under IIS.
So again, there are ways to configure LocalDB to make that work, but what we want to do is have our application work with the
SQL ServerDeveloper Edition that I installed. So finally, the application comes back and says, sorry, but there's a problem trying to
establish a connection to SQL Server. The server was not found or not accessible. The server was not found. So let's look at how to
configure this application to use the other instance of SQL Server that we have installed.
Configuring ASP.NET for Production
Earlier in the course, we saw that we can use a special file in an ASP.NET project, the Web.config file, to configure settings for our
application, like a database connection string. And then when we published our application from Visual Studio, one of the files that
Visual Studio will include in the published operation is that Web.config file. So if I look in the folder where I have published the
application, so in the web/OdeToFood folder, I will find Web.config, and you might think, well, this is now where I am running this
application, this is where I pointed IIS when I said set up a newwebsite called OdeToFood. And so if I modify this Web.config file
here, that will make changes to the application that is running, and that is true. If I modify the connection string in this
Web.config file, I will change the database that my application is trying to reach. However, what you have to be careful about
is application updates. What happens the next time someone publishes into the same folder? They're going to overwrite thechanges I
made in Web.config with whatever changed are in Visual Studio currently. Now there's various ways to manage and solve that
problem. Let me show you one way to do this that is built into Visual Studio in ASP.NET. So if I come to my OdeToFood.Web
project, there is my Web.config file, but notice I can expand this node and there's actually two files that are hidden behind
Web.config, and that is Web.Debug .config, and Web.Release .config. These are known as Web.config transformation files. So
these are transformations that Visual Studio will apply to Web.config when it publishes Web.config for a given configuration.
In other words, if I publish this project in debug mode, I can add settings that are specific to debug mode inside of
Web.Debug .config, and they will get applied to my Web.config. Likewise, when I publish in release mode, I can add
special instructions to Web.Release .config to make changes to the Web.config that is published for my application. So if I want to
consistently use the same database for my release mode production configuration, I can add an instruction into Web.Release .config
to make sure that my production mode database is always the database in the connection string in the Web.config that is produced.
Let's open us Web.Release .config. What we're seeing is lots of comments to describe the capabilities of a
Web.config transformation file. And of course, there's going to be additional capabilities that I don't show you in this particular
module. But what we're seeing here is an example of changing the connection string that is in Web.config when I do a release mode
publish operation. So all I need to do is uncomment this bit of code, and I will now be able to change a connection string that has the
name MyDB. So that's not the exact name that I want to change. If I come into Web.config and look at the connection strings I have
configured, the name that we decided to use was OdeToFoodDbContext. So I'm going to highlight that and press Ctrl+C to copy
that. Come over into Web.Release .config and paste that here. So in a release mode, build and publish operation I want to change
our connection string named OdeToFoodDbContext, and I want to set it to the following connection string. That's what this
transform is saying. It's saying go out and match an element by name in the regular Web.config file, and then set the attributes on
that particular element to match what is here. And now we just need to make a change to the connection string. So what is my
data source? Well, instead of being LocalDB, I want to change my data source to be this machine. We've already seen that I
can connect to this new instance of SQL Server that I have available, SQL Server Developer Edition, just by specifying a server
name of dot. And then what is the catalog that I want to use? Let's again use a database named OdeToFood. And finally, how do I
want to connect? Well, I would like to use integrated security, but this could be a little bit tricky with IIS. So there's two different
approaches that I can use to connect to my SQL Server. One is to create a user on my server and a login so that when I specify a
connection string, I can say that the user name equals something, and that username is going to have a password. I'm not a big fan of
usernames and passwords to access databases. Usernames and passwords have to go into configuration files and configuration files
all too often end up in source control, which is a problem when you publish your username and password. So instead I am going to
stick with integrated security, but now I need to make sure that SQL Server will accept the connection from the identity that
my application is running with. And remember, my application is going to run in an app pool named OdeToFood, that's what we
saw configured inside of IIS. And so I need to make sure that SQL Server will accept this OdeToFood IIS identity and will allow
this identity to create a database because that's what the Entity Framework is going to do when it arrives on that server and sees
there is no OdeToFood database. Of course in a real production environment ifyou're working for a larger organization and a larger
team, you can use tools with the Entity Framework to generate a script and use that script and pass it through a DBA to create the
database. But my goal in the next clip is going to be to configure SQL Server to allow my application toconnect and create a
database, OdeToFood, with all the tables it needs. Before we get to the next clip, however, I also want to point out this other bit
of transformation down here, which applies to the system.web compilation element, and this element that is commented out,
which applies to custom errors. So it is a good idea to include this transformation that changes your custom errors. So I'm going to
uncomment out that bit. And that is because what we're seeing from our application is typically not something that you want a user
to see. So just to remind you what we're currently seeing in the application is a very detailed error message that even includes a
stack trace, so exactly what happened inside of ourapplication. This is not information that we want to give out to just anyone
who's trying to use this application. This information is really intended for developers only. And with ASP.NET, there is a way to
control what happens when there's an unhandled server error like this, and that is with the customErrors section. What we can do
instead of displaying that detailed error message that ASP.NET provides is instead display some sort of friendly error page. So if
I create an InternalError.htm file and use this bit of Web.config transformation, I can show a friendlier error in
production.Something I want my everyday users to see when something goes wrong. So I'm going to leave this customErrors
section in place. But now let's go configure our database to allow OdeToFood connections.

Configuring a SQL Server Login


We want to configure SQL Server Developer to allow a connection from our OdeToFood application that's running in IIS. In order
to do that, let's go to the SQL Server Object Explorer where we already have a connection established to the SQL Server that I want
to change. And what wereally want to do is add a new SQL Server login. So the easiest way to do that is to come into Logins, right-
click, I'm going to say that I want to Add New Login, and Visual Studio will generate some SQL that I can execute to create a new
login. Now this particular login, this particularcommand, is the type of command that you would execute when you want to create
a username and password type of login. That is not what I want to do. What I want to do is create a login that is based on an existing
Windows identity, and the way to do that is to say that I want to create a login, specify the Windows identity that I want to use, and
then tell SQL Server this identity is from Windows. But now I need to specify the exact login that I want to select from Windows.
So what is the identity? In other words, here's one identity, which is desktop-some number\scott, but what I need is the identity for
my application pool. So coming back into the ISS Manager, I just want to show you, every application I create, IIS can set up what
is known as an application pool so that every application has a different identity. So the OdeToFood application pool, as long as this
is set to ApplicationPoolIdentity, it's going to have an identity that is unique to that application pool. So the identity for OdeToFood
is different from the identity for the default app pool. And this is how you can separate and isolate applications, so any application
running inside of theOdeToFood process, just because it's an IIS it's not going to be able to access the same databases that might be
in the default app pool because they are going to have two different identities. So how do I specify this OdeToFood identity when
I'm telling SQL Server about the login that I want to create? Well, the syntax for this is to say that you're creating a login whose
name begins with IIS APPPOOL\, and then the name of the application pool. So in this case the application pool name
is OdeToFood. And what I want to do is execute that little bit of SQL. I can do that I believe with the shortcut key Shift+Ctrl+E. I
can also come up here under the SQL command and say Execute. Yes, the shortcut is Shift+Ctrl+E. I have now created that login.
And now I just need to give this login some permissions so it can perform any activity that it needs. What I want to allow is I want
to allow the Entity Framework to connect to the server and then create a database for me. So again, in other environments whereyou
have DBAs and operation teams, you probably want to generate scripts for your database and execute them in a more controlled
fashion. That's certainly possible with the Entity Framework. But again, for me in this course, in this scenario, I'm more than happy
with the Entity Framework creating the database for me, but I have to tell SQL Server that this OdeToFood login is allowed to
create a database. And the way to do that with SQL Server is to issue a command to alter a server role, so there is a server
role known as dbcreator, and any logins that are in this role have the ability to create a database. And from that time forward, the
login will be the owner of that particular database that it's created and will be able to perform any operation that it needs. It can write
data. It can read data. It can create tables inside of that database. But I do need to tell SQL Server, please, alter the server
role dbcreator. What I want to do is add another member into this role, and the member that I want to add is this login that I just
created, so IIS APPPOOL\OdeToFood. Once again hit Ctrl+Shift+E, and that command is completed successfully. So now I have
a Web.config file that tells my application to connect to the SQL Server Developer instance on this machine as OdeToFood
with integrated security. And I've also told SQL Server about this login, so SQL Server should accept this login. Now all we need to
do is republish the application to get those Web.config changes in place, and then retry the application.

Running in Production
Inside of Visual Studio I've saved all the files that need saving. Let me right-click on the project that I want to publish. Notice the
previous publish operation that we completed has saved into a profile. So anything that I configured about that publish operation,
those settings have been saved. I can create new published profiles, I can rename and delete published profiles. So I might
have several different publishing profiles associated with the project, one to publish in the QA and one to publish into production,
and one to publish to a different server that I use for testing. We just have this single profile that we created earlier in this module. It
was named FolderProfile. I should probably rename that, but let's just go ahead andpublish again. This will just take a second as
Visual Studio does another build and copies those files out. Again, if I come out to the file system, I should see that the timestamp
for Web.config is updated, and it is. Let's even just open that up with Visual Studio Code real quickly to take a peek. And if I
bring Visual Studio code over here, I can see my Web.config transformation is working because now my
OdeToFoodDbContext connection string is not pointing to LocalDB, instead it's pointed to the local instance that is running on this
machine, so that's good. And now if I come over to my web browser, I'm hoping to be able to refresh the home page of the
application and see a response that doesn't involve an error message. It might take a moment to make this first connection for the
Entity Framework to set up the database for me, but I am back to the point where I have a running application and I have
0 restaurants in my database. But just to verify, let's open up Visual Studio. Let's come to SQL Server Object Explorer. Let's refresh
the list of databases that are available. And there is OdeToFood. And there is my Restaurants table. So it looks like everything has
been created properly and everything is operational. And now all I need are users who can come in and edit and add some new
restaurants for me. And that brings us to the conclusion of this module, and also of the course. I hope you enjoyed this course, and I
hope it givesyou everything that you need to develop with ASP.NET MVC. I hope you have many successful projects ahead of you.
And I want to give you a sincere thank you for watching this course through to the end. Thank you.

You might also like