ASP.NET Core MVC Course (.NET 5)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys and welcome to my course on introduction to asp.net core mvc and we'll be using dot net 5. i have seen many people struggle with the concept of mvc or getting to know how dot net core is different as compared to classic.net do not worry i have you covered if you need an introduction on what are the basic files and folders in a dotnet core project or how do you add database to the project how do you connect with entity framework core and much more before you take this free course i want you to be familiar with basics of c sharp and have a basic understanding of how sql queries work and sql server if you have that then this course will be easy to follow along before i walk you through what will be covered in this free course i would appreciate if you would like and subscribe to the channel so that you will be notified for all of the new free content that i will be posting that being said let's take a look at what we'll be covering in this free course we will first start with the fundamentals of asp.net core and the reason behind its evolution after that we will see what are the files and folder structures and we will understand what are basic terminal lodges like pipeline middlewares routing etc in a.net core mvc application once we get our solid foundation then we will add database to our project using entity framework core with that we'll be able to perform crud operations which stands for create read update and delete those are the basic topics that we'll be covering in this free course but that's not it once we have a functional crud operation website we will be deploying that to azure to see everything coming live with our database so we'll be building a website and will be deploying it to azure but along with that the most important thing is assignments and error solving i will be giving you assignments to practice the basic grud operations and you'll see common errors that we see and how to resolve those so join me in this exciting journey of learning asp.net core mvc with net core 5. before we get started i want to show you where you can get all the project resources if you go on.netmastery.com and courses i will have all of the courses listed right here now the free version that you'll see is a free version of the complete course asp.net core mvc up and running part one if you click on the details here and if you click on github code you will have the complete code we won't be building everything in this free course but if you go on the comments here and if you scroll down you go to the older comments you will see exactly on what was being changed like this section is included and if you click on here you will see what was changed in that git comment so if you face any issues you can come on github and you can check everything there one place for all the resources will be dotnet mastery if you click on details you will be able to get all the course content and the github code along with live preview of the course so that being said now you know how to get all of the project resources it is through dotnetmastery.com before we get started let's understand on what are all the softwares that we will need for this course the first software will be sql server 2019 you can also use any older version of sql server that's fine with me but if you want you can download the latest version scroll down here and you can install the developer version since it is the free edition once you have sql server then we need visual studio 2019 now the net core version that we are using is dotnet 5 and that is available in preview right now since it has not been released yet so for that you will need visual studio 2019 preview you can come here and download the community version and install it along with that you will also have to install.net core5 so you can install this and right now the preview version is preview 5. but the course that we will be building was built using preview 4. because of which in the course you will see i installed packages and everything for preview 4. but what you need to do is when you create the project whatever preview version you use make sure to use that same preview version throughout the course in all the packages or the installation that we do once the dot net core 5 is released i will update this and let you know to install.net core 5 and not to work with the preview version that being said if you do not want to work on the preview versions and you would rather work on visual studio 2019 you can follow along with the course as well for that you'll install visual studio 2019 and net core 3.1 the course will be compatible with that as well so that's all the tools and technology that you will need install them if you do not have them and join me from the next video in this video i want you to walk you through the journey of dot net core dot net core is probably the biggest change that dotnet language has encountered in 2002 microsoft introduced web forms which was a revolution at that time but as the time progressed there was need to organize things and with other drawbacks in picture came a new architecture which was asp.net mvc now even though i love mvc it had its flaws like it was created on top of the components for web forms because of that it was tied to iis and windows but as the web evolved microsoft had to keep up with the change with that finally in june of 2016 microsoft released asp.net core and it was the first version now asp.net core is built on top of the new dotnet core framework it is cross-platform version and hence it is not tied with windows also dotnet core was built with cloud in mind so it is extremely ravished with that then in august of 2018 microsoft released.net code 2.0 and microsoft team has been very active with releasing the new version as you can see in september of 2019 dotnet code 3 was released in the intermediate versions there was darknet code 2.1 and 2.2 there was quite a big change coming from 2.1 to 2.2 with respects to identity but with all the versions upgrading to the new version has not been that difficult then in december of 2019 dotnet code 3.1 was released which had a long-term support finally in november of 2020 dot net 5 will be released this dot net core 5 is right now in the preview version and we'll be using that to create our project so that is just a small journey for the dotnet core frameworks that have been encountered that being said why one should use dotnet core as compared to the classic.net there are quite a few advantages first is the asp.net core is fast and open source next benefit is it is cross-platform the classic.net was tied to windows and iis but when asp.net code was rewritten it removed that dependency with asp.net core we get the built-in support for dependency injection dependency injection saves a lot of time and it is extremely helpful as we proceed with the course you will see the benefits that dependence injection brings to the picture then the updates to new versions for dotnet code are easy because of that you can always keep up with the new versions dotnet core is also cloud friendly when asp.net code was rewritten it was written in a way to make sure that they had the cloud architecture in mind another benefit and one of the most important one of asp.net core framework is its higher performance with the new enhancements as well as upgrades the code actually gets much more optimized that results into improved performance the asp.net core compiler will eventually optimize the entire code whenever the code is recompiled using asp.net core framework asp.net core's actual performance is multiple times more than any of the famous framework implementations because of that it is clear that microsoft has quite a long term plan with this asp.net code technology so with that let's continue learning in the next video what we want to do first is we want to create our project so for that we will open up visual studio 2019 right now i am on the preview version because we do not have the dotnet 5 released so we'll be using the preview version with the.net 5 of preview as well so in here we will create a new project then we have a list of all of the templates that are available what we want is asp.net code web application you can also search for that if you cannot find it once we select that we will hit the next button and then we need to give project name location and a solution name i will call this as rocky and i'll change the location to where i want to save it so i'll select the location and we will hit the create button once you hit the create button it will give you more options that you can configure for asp.net code web application right here you can see the version which is asp.net core 5. along with that you can see right here we are on the preview version right now now if you'll be taking this course in the future preview versions might be different so make sure that you select the most latest preview version and then in all the other places make sure you use that exact preview version that being said once you have the dotnet core and asp.net core 5 here on the right hand side you can select authentication if you hit change here you have no authentication individual users account worker school or windows authentication now i could go with individual users account and get a built-in authentication but i want to set everything up from the scratch so we'll go with no authentication and then later in the course we will add authentication that being said in the advanced we have the configure for https we will select this we do not want to go into docker details right now so i will skip this next i will enable the razer runtime compilation now previously enable razer runtime compilation was not available here and you had to add a new get package for that but now they have added this in the options and i think this was a much needed move because razer runtime compilation is one of the core features that you need when developing application this enables that if you make some changes to javascript file and if you save the application go back and refresh it automatically populates the changes rather than restarting the application so that's enough details about that we will make sure that this box is checked and then the main thing here is what template that we want now here there are quite a few template we can start with an empty project api project web application which is razer pages or mvc application i will go with the mvc application and this will give us a basic setup for an mvc application we don't have the authentication and once everything looks exactly like i have let's hit the create button this will create our project and it will add few files and templates to our project great so our project has been added and right here we see quite a few files let's continue working on this in the next video our project has been created and it's time to take a look at the files and folders that we have inside our project the first file will be the project file that we will be taking a look at for that if you right click on the project you will see the option of edit project file other way of accessing that file is just double click on rocky that will load the project file by default now here in the project file you should notice the target framework that we are using is net core f5 so this will be the dotnet framework that we will be using for our solution if you are using 3.1 or 3.0 that is the version you will see right here then we have few more elements and the other important entity will be the item group item group will have all of the third-party packages that we will be installing in our project right now when we created the project we selected the runtime compilation on the project options because of which it has added that nuget package right here when we will be adding more packages like we'll be adding database packages email packages all of those will be added in the item group and we'll be watching them once we add new packages in the upcoming videos when you have to add the package you do not have to come here and manually add the line we will be doing that using new git packages that being said this looks good for our project file let's continue with the other files in the next video next important file that i want to show you is the program.cs now we won't be going through all the files in the same order but i will be going through them in an order that will be easier for you to understand the next file we'll be taking a look is the program.cs if we scroll down here you will see that there is a main method main method is more common in console application and the reason you see that here is initially.net core application starts as a console application the main method configures asp.net core and starts it the configuration is done by calling the create host builder and as you can see this is a method in the program class which returns an object of ihost builder on this object build and run are called and then onwards the application will become an asp.net core application the create host builder calls default builder which configures the web host using defaults also you can see the web builder is configured using the startup file before we take a look at the startup file in detail let's understand a core concept of asp.net core which is dependency injection in this video before we take a look at the other files i will introduce you to a new concept which is dependency injection asp.net core implements a simple built-in dependency injection container dependency injection is an integral part of asp.net core architecture dot net core injects objects of dependency classes through constructor by using the built-in ioc container that being said let me try to explain in simple words what dependency injection is and what benefit it brings let's consider a scenario without dependency injection so in any application let's say we have three pages right now and we have some common functionality that we want to use across all the three pages like email and database access now let's imagine that on all of these pages we need access to database first so what we will do is we will create the database object on all the three pages and in our case we'll call the class name sdb then we'll have to do the same then create object of the email implementation that we have in all the three pages for the email class now consider a scenario what happens if in future you change the implementation of how you access the database or email based on the current configuration you might have to make changes in all the three pages which is a big mess another issue here is on each page you have to deal with creating the object managing them as well as disposing them and that would consume time in each and every page which is a bad approach so that being said what is a solution to avoid all of this the answer is dependency injection with dependency injection let's first see how the scenario would look like we will again have all the three pages and the email and database functionality here along with all the things that we had before we will have something new which is a dependency injection container then we will have the email and database functionality but rather than having them in just classes we will also have an interface for email and database then our classes will be implementing those interface and we will register the interfaces in our dependency injection container as you can see so we will tell dependency injection container that i email is an interface and email is implementation of that interface when any page will need to access these functionalities it will just ask the dependency injection container to create object of this functionality and directly give us the object to use so inside the page we will actually be using interfaces and then dependency injection does all its magic of passing the object when the website needs it that way we do not have to deal with creating the object disposing or managing that object inside our pages our pages will look very clean with just the interface and all the instance and implementation will be done by the dependency injection container now in future if you want to change or replace the email class you do not have to make any change in the pages all you have to do is you just need to change the implementation that you do in the dependency injection container in one location also as i have said before creating and disposing object is now the responsibility of the built-in dependency injection container and we do not have to worry about it anymore which is a great relief so you can see that there are lots of advantages that dependency injection brings to the architecture that being said with net core we have the built-in dependency injection container now how do we register these dependencies or where do we register these dependencies let's understand a part of that in the next video we had to take a detour to understand dependency injection before we understand the next file which is startup right here you can right click here and go to the definition or you can open up the startup file from here itself now startup class as you can see is a basic class with no extensions or implementations of interface but the first thing that you notice if you scroll down is that there are two methods the first one is the configure services and the next one is the configure method both of these methods are invoked automatically by asp.net core configure services gets called first we will be registering all the dependencies with dependency injection container that is built in in asp.net core within the configure services so that is why i wanted to introduce you to dependency injection in the previous video because configure services is the place where you do the registration of your service if we switch back to the powerpoint the step that we do when we register our email and database with interface as well as the implementation that is the step that we will do inside configure services method so inside the configure services method we can add services to the collection of services services are basically any functionality that you want to register so other parts of application can use it as we saw it could be email database and much more we will be registering the services provided by the.net core framework as well as custom services that we will create as of now you can see right here we just have one services which is add controllers with views and with this we register mvc service to our application we will be adding more services here but before we dive into mvc in the next video let's understand the configure method but remember that configure services method gets called by the runtime and we use this method to add services to our container that being said let's continue in the next video in the last video we took a look at configure services next method that we have here is the configure method here we see the i application builder as well as the iweb host environment environment we are using only to check if it's development or if it's something else based on that we are configuring the pipeline but the i application builder configures the http request pipeline of asp.net core the pipeline specifies how the application should respond to http request let's take a look at this with an example so in order to understand what the pipeline is let me switch to the presentation here we have different browsers here and then we have a pipeline the pipeline specifies how the application should respond to http request when your application receives a request from the browser the request goes back and forth through the pipeline in the pipeline you can add items that you want pipeline is made up of middlewares and mvc is a middleware itself so if we want an application to be built using mvc we need to add that middleware other examples could be authentication middleware authorization middleware session middleware static files middleware and much more so what exactly happens is when your request will go through each middleware it can get modified by them and eventually it is either passed to the next middleware and if that is the last middleware in the pipeline the response is returned back to the server let's take a look at the few middlewares that are already added in our application so if we switch back to the code inside the configure method first we are checking if the environment is development then we are adding a middleware for developer exception page else we have the exception handler which displays a custom error message because we do not want to show them the developer or the coding error then the next middleware is use https redirection this forces the user to use a secure line and then we are adding static files what i mean by static files is that any web project needs styling javascript images and much more so all of the static content will be served by our application only because we added the middleware to use the static files then we are adding the routing middleware followed by authorization middleware you can see authorization is added before the end points right here and that is because order matters when it comes to the middleware when the request comes in it is passed from the first middleware to the second to the third and so on in endpoint we configure the default route for our application that being said before we understand the endpoints in more detail let me explain you routing in the next video inside the configure method we have seen the use routing as well as use endpoints that being said we haven't seen the actual mvc routing and how that works endpoint routing has been introduced in asp.net core 3. in the initial version of asp.net core routing was a part of mvc but it has been separated out to make routing available to all the middlewares and not just mvc whenever a request comes in it hits an endpoint and that endpoint is processed by the middleware before we get into those details let me switch to presentation and i can give you example of routing the url pattern for routing is considered after the domain name so in this case it will be after localhost and the port number which is five five five then in the example url that we have we see category forward slash index forward slash three in an mvc application the first thing that you will see will be the name of the controller after that we will have the name of the action followed by the id also keep in mind that id is an optional field some of these fields can be optional and if they are not present it will take the default value like if an action name is missing it will default the action name to be index you can change the defaults if you want but if we switch back to our application and if we see the end point that we are using we have a default pattern in which we have the controller name defaulted to home action name defaulted to index and we have an id property which is optional so with that in place let's try to see some more examples here the first example we have forward slash category forward slash index so in that case category will be the controller index will be the action we do not have anything for the id so id will be null next what we have is only category in that case the controller will be category controller and action will be defaulted to index action and if no id is present it will be null then we have category forward slash edit forward slash three we have all the fields here controller will be category edit will be the action and id will be three in the last example we have product forward slash details forward slash three again we have all the three entities controller will be the product action will be details and id will be three now in mvc there is a route table which tries to match endpoints to find out where to pass the request to be on track here if we have a url like this in mvc home would point to a controller and index would point to an action method as we saw in the last slide now if you are not aware about what is a controller what is an action method do not worry right now just understand that this is one way of routing we will be getting into mvc details very shortly but asp.net core is now more than just an mvc application it can also have razer pages and signalr that being said it is possible to have all three in a single application all of these technologies have middlewares that register endpoints so if we switch back to our application right here we see a middleware of use routing in startup.cs so let's imagine at some point we hit this middleware at this point the request will inspect all of the registered endpoints they can be endpoints registered by mvc or any other technology it determines whether it should send the request to mvc or any other technology then for all the middlewares that will be executed after this we'll know that end point has been selected like mvc or razer pages and then later on when it hits the end point in the use endpoints we will register the end point and then when the request arrives at this point it will be processed by the end point that was selected in use routing so in expression we have the end points and we have an object for the options on this object there are several extension methods that are available to register different endpoints like right here we are registering the mvc then we have other endpoints for razer and signalr as well we will be adding razer endpoint later in the course and within the controller which is the mvc we have added a default pattern so by default it will load the home controller and index action if nothing has been loaded so here we also have registered a default route for mvc application which has a controller name home and an action method called as index this map controller route uses routing table to match against the request this is the basic overview of routing middleware that we have that being said before i actually run the application and walk you through routing in demo let me finish the overview of the other files and then we'll get back to routing and view it live in action in this video i want to introduce you to appsettings.json this is the file in which we'll be adding all of the connection strings and static files like secrets that we want in a production application you can move this to words or secrets but we'll be using app settings for this course here right now we see the logging and in that we have some things that have been configured we will be adding connection strings along with other things in this course inside the app settings whenever there are any keys or anything that we want to use throughout the course it is a great place to store them right here that being said we'll come back to this file and we'll be adding new things in the upcoming videos next what we want to see here is we have a folder called www root this folder has been created since we selected the mvc application in here if you expand this there are more folders that has static files for our application static files could be css javascript or any of the third-party libraries you can also have images here or html templates if you remember in startup.cs if we go there we added a middleware use static files and that was added so that the application can use the static files that we add inside www root this www root folder will be the root folder in application for all static files none of the c sharp files will be placed in this folder this folder is only meant to serve all the static files for our application so we'll be using the static files folder extensively throughout the course when we have to add images or we want to add any class libraries or we want to modify external css once we have that the last thing that we have is launch settings.json launch settings.json is inside the properties folder and if we double click it displays different profile in which we can run the application like here if the profile is iis express it sets the environment variable for that profile to be development this way you can configure more profiles that you want with the url as a support and other functionalities also when we will run the application right here we will be seeing all the profiles that we have set up inside the launch settings so right here you can see iis express and we have the rocky profile if you want to modify them you can modify here directly or you can also do the same if you right click here and here if you go to the properties we will be having those profiles in the debug tab so right here you see iis express as well as rocky we can set the browser url and we can set the environment variables that we want here we have the other settings which you can set from that page or we can do in the launch settings.json now we won't be tweaking this much because this is more related to deployment and if you want to add more environment variable for like staging another environment but we'll just keep it with the basic for this course so with that we have covered all of the files that we see in the project except three main folders which is controllers models and views and as you would have guessed this is what mvc stands for which is model view and controller that being said let's understand the architecture of an mvc application the first thing in mvc is the model model represents the shape of the data a class in c-sharp is used to describe a model the model component corresponds to all the data related logic that user works with this can represent either the data that is being transferred between view and controller or any business logic related data model would also represent all the tables of the database so if you have 10 tables in the database you will have at least 10 models on top of that there is also more complexity but we will go into those details later on in the course so if a class is a model then all the properties in that class will be all the columns of a table so that is the simple relation that you can think about model right now then we have the view view in an mvc is a user interface view basically means whatever you see when you click a web page the ui that you see that will be represented by the view view in asp.net mvc is html css and some special syntax which is razer syntax so main thing about view is that it represents the user interface logic of your application finally we have the controller the controller handles the user request typically whenever a request comes in like user clicks anything it will raise an http request which will be handled by the controller the controller then uses the model as well as view to process the request and then it returns back an appropriate response so controller acts as an interface between model and view to process all the business logic incoming requests and it manipulates the data using model and interact with the view to render the final output this is just a brief overview of how model view and controller interacts so just to summarize what happens is first a user clicks something on the website so a request comes to controller controller will always be the main entry point in an mvc application and in controller it will hit any of the action methods that we have defined inside the controller now controller will uses the model and it will fetch all the data that it needs to display in a view then it passes that data to the view so that view can render the final page that user can see then view will send the request back to the controller and then based on whatever is rendered a response will be sent back and user will be able to see the page so you can see controller can be treated as heart of your application with that in place in the next video let's run our application for the first time and see how model view and controller interacts and how routing works now before i run the application and show you routing in detail let's take a look at the folders that we have with model views and controllers so right here we have a home controller and in the model we have the error view model whenever we'll be adding new models or if we want to add a new table in the database we will be adding models inside this folder controller as we know is the heart of the application in controller if you expand this you see there are many of the functions these are known as individual action method so a controller has action method if we go back to the routing template that we had we had the controller name and the action name so what means is if someone calls index then they can call it home forward slash index and the control will hit this breakpoint when the url is submitted and once the control gets here we are just returning back the view so this view will be inside the views folder and inside the home folder the folder name will match exactly as the controller name so it will look for an index view inside the home folder inside views and that will correspond to the action method that we see right here so what we have in the index view is if you open it we have a title we have welcome here and then we have learned about building web apps with asp.net core let's run this and make sure that this is actually working so let's run our application for the first time and great we see that page is loaded now right here in the url we do not see any controller or action name and the reason is if we go back to the application in startup we configured the default to home controller index action so that being said if you add a debugging point right here and if you go back and press enter you will see that it hits this breakpoint so it is actually calling the index action method inside your home controller that being said let's continue here and the view is loaded now what will happen when we click privacy you can see in the url on the bottom here it is going to home controller and privacy action method so right here inside home controller we have the privacy action method which just returns back a view that view will again be inside views home and we have the privacy view and this is what we should see when we click that let's go back and click here now you can see the control is getting to the privacy action method and if you hit continue the privacy view will be loaded great so we can see how routing is working so far right now we do not have any id even if you add an id it will still load the privacy because id is optional so if you have it or if you do not that doesn't matter so with this routing is making little bit more sense on how the controllers and view routing works one thing you should always remember is if your name is home controller you should have a folder within the view with the name home and in there you will add all the views corresponding to the action methods inside the home controller that being said right here there are few more views that i want to explain you let me do that in the next video in the last video we saw the routing and we saw how the model and views are integrated together that being said in the views we have a shared folder this shared folder is used for partial views partial views are similar to user components if you are coming from classic c-sharp so it is basically a view that you want to consume in multiple places in your application along with that we have a special partial view which is underscored layout underscore layout is the default master page for your application so in here if we scroll back to the project that we are running we have the header here so the header and footer are included in underscore layout right here we have the header then we have render body and we have the footer along with that in underscored layout we have some styling and javascript that can be used throughout the application so in future if you want a styling or a javascript functionality that you want to use throughout the application this is the place where you will add it other than underscore layout we have a partial view which is validation scripts partial this partial view just has the reference to some of the jquery for validation we will be using this in the future videos then we have error.cs hdml and this is just a common error view that we have in developer mode so that's about the shared folder views we will be adding more partial views in future that being said inside the views folder we also have two important files first is the view imports the purpose of view imports.cs hdml file is to provide a mechanism to make directives available to razer page globally so that you don't have to add them to the pages individually so right here it is adding the tag helpers so with this all the default tag helpers that asp.net code team provides will be added to all of the razer pages in your application if you do not have this then you won't be able to use tag helpers in your project an example of tag helpers can be seen in underscored layout if we expand the header right here you see this tag helpers asp area asp controller asp action these are all the tag helpers that make the binding look like html language but it does the binding with your c sharp code tag helpers is an idea that microsoft team has adopted from other languages after looking at the success like angular and react so if in future if you add more custom tag helpers you can register them here and they will be available for use throughout the application that being said we'll go to the next file which is view start the main purpose of view start is to set values that all the other views will have to use if this view exists and it is under the views folder it enables us to set the property that applies to all the views in the system right here a most common underscored layout view will set some properties the default one in mvc is the layout page however you can also do complex thing in view start for example you can say that for a specific controller you want to change the layout page you can add if condition check the controller name and do complex logic but we'll just leave it simple for now so here we are defining the default master page for the application is underscore layout right here so if you change this your master page could be changed using the layout property in view start also what you can do is you can add a view start inside the folder as well and then that file will take precedence so with that i believe we have covered all the files that we have when the project was created now this has been a lengthy section and it was mostly theoretical with very little exposure to routing and the project but this won't be the same moving forward moving forward everything will be hands on and we will be coding everything and exploring asp.net core in detail so that being said let's get started with everything from the next video now that our project is created and we have an overview of all of the files that comes by default let's add our model now what is a model model will represent a table that we want in our database so for our application we want to add a table in our database for category in there we will have three columns we'll have category id category name and display order as i told you before we will not be touching the database directly if we have to make any change to our database or even create the database we will be doing that from our code so for that what we will do is first inside the models folder here we will right click and we will add a new class file and we will call this as category inside category what are all the columns that we want all of those columns will be properties of this class so we can use the snippet prop and press tab twice then we have a property that is generated first we want the id which will be category id or i can call this as mid in sql server for columns you can have them as identity an identity column will mean that you do not have to pass those values whenever you add a new record it automatically increments by 1 and creates that but you only have id here how do you tell the database or entity framework code that this column needs to be a primary key and it needs to be identity for that we have data annotations you can see right here it is inside system.componentmodel.data annotations if you press enter here it automatically adds that namespace right here once you add data annotations it tells entity framework that this column needs to be an identity column and a primary key for our table entity framework also has default so if the name is id or if the name is category followed by id then it automatically adds it as a key entity so even if you do not add this it will be added by default but i always like to be explicit about it so that when someone sees our model they can get a better idea using this there are many more data annotations but we won't go into those details right now i want to start from all the basic and then we'll go into the advanced concept next what property we want we'll press prop again and tab twice next we want a string and we will call this category name you can call this category name or i'll just go with the name last property that we want is an integer and let me call this display order now we won't be using this but i'm just adding a new property so i can show that to you guys so now what we have is we want to create a category table in the database and we want these three columns in that table but how do we do all that let's take a look at that in the upcoming videos now we have created our first model which is the category model we need to push this model to our database but first we do not even have a database for our project so let's go to sql server management studio and right here let's connect to a server now here one thing that you should remember is the server name i have dot right now but i can also change it to local db ms sql localdb now for some this might be the server name they are able to connect to and for others it might be a dot i have both of the options so i can connect to a dot as well as i can connect to the local db ms sql local db great you can see both of these options work for me once you have that determine which of the server you want to use for our course we will be using the dot so if you expand the databases we have two databases you can expand this you can take a look but what we want is we want to add our own database right here so how do we do that for that we need to add a connection string in our rocky project so right here whenever we have to add a connection string we'll be going to appsettings.json this is the file where we will be adding all of the secrets or connection strings for our project now once you move this to production you can move this to appsecret.json but for the course app settings.json is a perfect location now the next question is where do you define connection string in here for that right here we need to create a connection strings and we can assign it inside the parentheses now in here we need to give a name so i will call this default connection and then within the double quotation we will write the connection string so right now we have server equal to and i will use a dot here because that is what we are using next thing that we have is the database name so we'll say database and what name do we want i'll call this as rocky after that we will set the trusted connection to true it will be trusted underscore connection is equal to true and then we will have the multiple active result sets to be true that's all we need for connection string now what i'll do is i'll copy and paste this one more time i'll comment this out and instead of dot here i will paste local db ms equal local db because this might be connection string you want to use if you wanted the different server we'll go with the dot now we have our connection string in place the next step will be using this connection string to actually create the database let's take a look at that in the next video now we need to create our database and we also have to push the category model to the database in order to do that we need a db context in our project dbcontext is provided by entity framework before we do that right here let me add a new folder and i'll call this as data in here we will right click add a new class file and i will call this application db context or you can call this any other name followed by a db context now this is just a basic class how do you make this class a db context in order to do that this class will have to implement or inherit from the db context right now that class does not exist if you do control dot here it will show you options to install packages so we need to include entity framework core in our project now there are multiple ways to do that first thing you can directly go here and you can click find and install the latest version next way you can go to tools nuget package manager and you can install the package if you know the name with the package manager console and if you don't know the exact name we will go to manage new kit packages for the solution in here what we will do is we will go to browse tab and we will search for our package which is entity framework core once you hit enter here the first package you see is microsoft dot entity framework core now entity framework code will not be the only package that we will need we will also need the package for sql server because entity framework core needs a database to work with so that will be sql server so right here if we search for sql server we will have a package microsoft dot entity framework core dot sql server so in order to install this package we'll click the project name and we will hit the install button now if you are on the preview versions make sure that when you created the project the version name for preview should match exactly like you created the project if you created the project with preview 3 right here it should be the preview 3 that you should be installing and not preview for that being said we'll switch to what we have once you make sure all of that is good let's hit the install button it asks us for the license we'll accept this and great package has been installed we see the error with db context but we will solve that later on now if you go to dependencies packages you see you have microsoft dot entity framework core dot sql server if you expand that you have microsoft packages and if you expand further you see that microsoft dot entity framework core is already installed the reason is because the sql server is dependent on entity framework core that's why if you install only sql server entity framework core gets installed by default now that the package has been installed if we close this and if we go to our application db context right here you click there and you will hit control dot for intellisense it says that you can now add using statement for microsoft dot entity framework core so with that we have added entity framework core in our project that being said we need to add some configuration here we need to create a constructor so we can type ctor you can see it is a code snippet for constructor and we'll press tab twice in here since we are implementing the db context we need to pass the db context options here and we need to configure the application db context class we'll call this as options what we have to do is we need to pass all of these options to the base class for db context now this will include connection string as well so we'll pass base and we'll use the options if you do not understand this do not worry it's just some configuration that you have to do in order to use the db context that's everything that we had to do to create a db context for our project right now things might not be making complete sense to you but just stick with me for few more videos and you'll see how easy and magical this is now the thing that is remaining is we need to create our category table in the database and we also have to create our database let's continue in the next video to finish the last step of our configuration now we have the application dbcontext class next what we want to do is we want to create the category table to our database whenever you have to do that you will come to the application db context once you have created the model and here we will create properties to push them to database so we'll do prop and this time the property type will be dbset in here what is the class name which is the entity so the entity that we want to create to the database is category entity and what name do you want to give to that table inside the database i want to call it the same name as category now by default the convention is to name it plural like categories but i like to name them same as the table name or the model in our project so that way we will be creating a table with the category name in the database this is all looking good and fancy but how will this come together for that we will be using our startup class file because we want to configure this db context to be used by our application when it starts and that configuration will always be done in startup class file so inside the startup class file where we have the services we will be adding a service for rdb context so here we have add db context and in here you need to pass the entity name which is application db context then we need to configure options on that property and if you see right here we are passing those options to db context so in startup what are the options we want to configure first thing is we want options that we want to use sql server so right here you will have to add the namespace microsoft dot entity framework core and then you need to configure the sql server options now sql server options does not need many things it just needs a connection string and that connection string is inside app settings.json inside connection strings make sure that you name this exactly and there is no spelling mistake or else this won't work once you make sure both of them are looking exactly like me you'll come back to startup and we have the configuration object here on configuration object we have an extension method get connection string what this will do is it will look into your app settings and it will go inside connection strings right here in there what key should it search for key will be the default connection so we will copy this come back here and inside double quotes we will paste default connection that way it will retrieve the connection string and it will pass it to the options for sql server so that's all configuration we had to do to add our db context and use of sql server to our project so with that we complete the configuration that was needed but right now the sql server does not have our database or the table for that we need to understand migrations whenever we will have to push any change from our website to our database we will be creating migrations let's understand them in the next video now we have added in our db context the category model so the next thing that we have to do is we need to add a migration to push that to the database in order to add migration we'll go to tools new get package manager and we will open up package manager console in here we will be adding our migration so for that we will add a command add migration and then we will give our migration a meaningful name what are we doing in the first migration we are adding the category table to database so we can say add category to database and we will hit enter when you do that you will see an error message it says the term add migration is not recognized as a name of command let function script file or operable program if you created your project with individual users account identity then you won't see this error because it installs the new git package that is needed for migration but since we did not do that we will have to install another nuget package so we'll go to the nuget package manager and we will search for tools we want to install microsoft.entityframework.tools right here this is entity framework core tools for nuget package manager console in visual studio make sure you install the correct version and great everything looks good so we will close this and if we go back to our application db context let me open the package manager console here let's try to run this one more time in order to run the same statement you just press the up arrow the build started build succeeded and it added our migration now this is entity framework code doing its magic you can see what it's doing is it is creating a table called as category and it has three columns first is the id column which is of type identity and nullable is false then we have the name and display order and it also adds a constraint to make the x dot id as the primary key so all of this magic is done by entity framework core it automatically converts your model that you have into migrations and then you can push this migrations to the database so how do you push them to database now for that if you go to package manager console here let me clear this out and the next command is update database so once you have that command and if you press enter it will push all the pending migrations to the database in case like ours where the database does not exist it will first create the database and then proceed further now if you have any errors while building the project you won't be able to get past the step because your project must build successfully in order to proceed so right here you can see it's done what exactly just happened let's understand that in the next video now that we have pushed the migration let's see what actually happened in sql server in here we see the new database which is rocky let's expand that and we have the tables now in tables you see we have created category table but entity framework code already added underscore ef migrations history here it keeps a track of which migrations are actually applied so that it can synchronize everything right now that will be just the name of the first migration that we added which is add category to database so we'll close this and then let's examine the category table it has the three columns that we wanted so it actually pushed our category model to the database and everything is looking good right now so remember whenever you have to make changes you first make the changes add a migration and then you update database to push the migration to the database so that being said let's continue in the next video before we start with anything let's run the application so if we go in the arrow here with the browser you can pick which browser you want for the application i will be using the new microsoft edge and let me run this and take a look at the result so our application is up and running and we see home and privacy what we want to do is we want to add a new tab here or we can replace the privacy tab with category how do we do that this navigation bar that we have is inside the shared folder inside views so if we go to views shared we have the underscored layout and right here we have the home and privacy here you can see the action name is privacy and the controller name is home what we will be doing is for category we will be adding a new controller so for that we'll go to solution explorer in controllers we'll add a new controller in order to do that we will have to stop the application and controllers add a new controller and we will go with the empty controller now what you need to do is we need to name our controller it should always end with the controller keyword so whatever is before that will be the controller name and we will call this category controller great so you can see our new controller has been created and in there we have an index action method how can we navigate to this controller using our url let's run the application and then if we want to go to the privacy action in home controller you can see the url is home followed by privacy so in order to go to our category it will be category controller and what is the action name that is the index action name but if you press enter right now you will see an error that view index was not found that is because we have added the action here but we have not added the view so inside layout what we will do is change this to category controller action we'll change this to index and we will call this category if you go back and if you refresh the home page let's go here this time the privacy will be updated to category but if you click on category you will still see that error message let's continue in the next video to fix this error message and add our view now if we try to navigate to category controller index action the view is not found so let's add that view for that it is simple you can do one of the two things first is inside views you can create a new folder with the exact name as the controller name which is category it won't be category controller it will be only category and then in there you can right click add a new view here and that will do the trick or simple way go to category controller right click on the action method select add view we will be using the razer view do not go with the empty option here and then you can see here we have some configuration first is the view name which will keep the same as index next you can use template when you create a view it can be create template edit details or delete we will be going with the empty template and we don't want any model classes right now if you select any of the other then you have to select the model class like if you want to create what object should it create should it create a new category if yes what should be the db context that should be used but if you go with empty you don't get those options that being said we have not used partial views right now so we'll leave this unchecked and option here is use a layout page if you check this and if you leave this empty it will use the default layout that you have so we'll just keep that and press the add button it will add few neoget packages for scaffolding and then it will create the index view one thing to notice is the view will be added inside a folder name with the exact name as your controller which is category that being said if you run the application now and if you hit the category you will see the page with the word index in there so if you hit category great you can see the view is being rendered so now that our view is added and our database is in place let's see how we can create a category let's continue working on the index page in the next video what do we want to do on the index page of category we want to display all of the categories that exist in our database right now we do not have any categories in our database but let's say we add some categories manually for our testing so we can go to database edit top 200 rows and we'll just give it a test name display order one will give it test to display order two we have two categories now so if you do select star here you will see two records let's see how we can display them here in order to display them we need to extract these values from the database so for that we'll be using entity framework and we need the application db context or the db context to do that so we'll go to the category controller and in here we need an object of application db context but thankfully dependence injection takes care of all of that so right here we'll just use application db context and we'll get that using dependency injection so right here we will be adding a private read only property and this will be for application db context we'll call this underscore db now we need to populate this property and we'll do that with constructor and we'll be using dependency injection if you go to your startup cs right here you have added the db context so you have already added that in your service container if you want to pull something from that container in the constructor you just write the class or the interface name so this one is application db context and we'll call this db what this object will have is it will have an instance of the db context that dependency injection would create and pass it to you in your constructor you do not have to worry about all the back end behind that asp.net core takes care of everything so you can just assign your local underscore db as the db object that is passed and then you can use this underscore db throughout your controller so we have the database object in underscore db what if we want to retrieve list of all of the category so in the index let's retrieve an i enumerable of category and let me call this object list obj list is equal to how do we retrieve that from database we will be using entity framework so we have the database object and in there you already see category if you just do like that it will retrieve all of the categories from your database and it will store them in this obj list let me copy paste it to the view and will return that list to be displayed in our view let's add a debugger and see if it actually passes anything let's run the application and let's hit category it will hit our debugging breakpoint and right now the list should be empty here that's good if we press f10 to continue to the next line if you hover now you see the list and result view it should have two values and these are the two categories that we added so you can see how easy it was we did not have to write a query like select star from category entity framework core takes care of everything just one line and you get all of the categories so even though we spend some time in configuration for entity framework and db set and db context you can see the advantage that it brings to the table and in future this will save tremendous amount of time as we will see so now we have list of all the categories and we are passing that to the view if you hit continue here you will see that we do not see any of the list that's because if we go to the index view we are not fetching that model or we are displaying anything in here other than index let's do that in the next video now we want to display all of the categories in our view so we are already passing that from our controller when we return to the view whenever you pass anything from the controller you need to make sure that you fetch it inside your view now how do you tell this view that actually a list of categories is going to be passed to you from the controller for that we will define at model on the top here in here m will be of lower case and then we will define what will be the model type here it's an innumerable of category so we'll say it's an i enumerable of category if you type just category this works but what i prefer is i prefer rocky dot models dot category this way you know the complete path for the category so in large scale application you are not confused now what will happen is the list that we will pass from here will be available on this view and we can display that so we can use some bootstrap styling and we can display a table we can add a div give it a class of container and we'll give padding 3 in here then we can add a div give it a class of row and padding top we'll give it four and in there we'll add a div give it class of column six we'll divide it in two pads we'll have another div class of column six in the first one here we will have an h2 tag and we'll give it a class of text primary and we'll call this as category list in here we want to display link to create new category that looks good then let me add some line here and then i'll display a table now the table i only want to display if there are more than one categories that have to be displayed so with razer syntax you can combine c-sharp syntax with the html for that you just write the add sign and then here we have the for loop we have for each loop you can see and we also have if conditions so we can use the c sharp if condition and we want to see if this has more than one category here the model was lower case but whenever anywhere else in the view if you want to access this model it will be a capital m so it will be model dot we just want the count on that if it is greater than zero that means that category exist so if the category exists we want to display a table and we can use bootstrap classes for table table bordered and table striped we can also give it a style of width of 100 percent inside here we have the t-head and we have the table row in which we'll have the header first one let me display category name followed by display order and we'll have an empty th so this looks good for the heading then we have the t body in body let's say you have 10 category so you want a loop that is iterated 10 times and you display all of the properties so like we had if with the razor we also have for each and we'll iterate through all the categories so we'll say variable object in model now what is model model is actually the i enumerable or list of category so right here we will add a tr tag and we'll display td we'll give it a width of 50 percent the first thing here is the category name so at obj dot we have the name in there we'll copy this paste it one more time we'll give it 30 percent and we can display the display order and then in the last one here td let's say we want to display the buttons to edit or delete a category but we'll do that one thing at a time then we have the if condition so we can add else block and we can just display in paragraph no category exists so this looks good let's run our application and see how things look like we'll go to category and we'll continue on our debugger great we see both of the categories here we have the create new category so we'll make this a button or a link and we'll continue working on this in the next video now we have worked on our index page and we are loading all of the page for that what were the two things that were needed one was the controller action method inside category controller and we needed a corresponding view what we want to do is we want to create a new page for creating a new category so for that the first thing that we'll do is we'll need a new action method right here so we can copy this and paste it one more time and this will be for create what happens in the create in create we will display them to empty text box to enter the name and display order for the new category they want to create that being said since everything will be empty we do not even have to pass anything to the view it can be empty so this make sure that this is get for create once we have added the controller let's add the view as well it will be the razer view and we'll keep it the same let's add this first thing that you do whenever you add any view is will that be a model needed for this view we are not passing anything from the controller but that doesn't mean we won't be using a model in the view here we will be using model which will be category so we'll go to rocky.models.category now why do we need a model here and the reason we need model here is whenever user enters any of the category name and display order and hits the create button we want to pass those values to our action method which will be a post action method for category and we want to create the category so here what we'll do is we'll add a form and it will have a method of post and where it should post we can explicitly define that using tag helpers tag helpers looks exactly like html but they are asp dash and then these are the default tag helpers that asp team provides so right here you can see there is a tag helper called asp action we will call this as create this means that when the form executes a post method it should look for a post action method of create we will add that in the next video but i wanted to point that out in here we'll use some bootstrap classes of border and padding three and in here we'll add div give it a class of form group and row and we'll add the heading here h2 give it a class of text info and we'll give padding left of three we'll call this add category now that we have that let's run this application and see this title if we go to category and we'll remove this debugging point right now we do not have the button to navigate to the create new category so let's do that in the index right here we have the create new category how do we navigate to that page in order to go to that page you will have to go to the action method which is create inside the category controller thankfully we have tag helpers for that so right here inside the anchor tag we have the asp action tag helper what action do we want to redirect to we want to redirect to the create action and that is inside the controller which is the category controller typically you would write the controller name before the action name that's how the navigation goes first what controller in that controller what is the action method once you have that you'll close the anchor tag after the create new category let's go back and refresh here and if you click here it takes you to your ad category let's add a little bit of styling here so we'll add a class of btn btn primary and let's see how this looks okay we'll also align this to right so we have text right and perfect so when you hit on create new category it takes you to the add category let's continue working on add category in the next video now we want to add the text boxes for adding a new category options like name and display order so we'll go back to our project and let's stop this now we will be doing that inside create we will be adding little bit of more bootstrap styling i don't want to spend much time on bootstrap styling so i will be attaching snippets with the course where you can get them and paste those bootstrap directly here in section 1 i have lecture project resources in which i explain how you can get all the snippets so right here we are on section 2 but if you go back you will have all the section so we will open up the add category snippet and we'll copy this go back to the create and make sure you add this after this form group and row and paste it here you can see it's not doing anything fancy if you save this and run the application you will see what exactly was done so if we go to category here and we go to create new create uc name display order and here we need text boxes and we'll create two buttons one button to go back to the previous page and one button to create or add a category so let's switch back here we want to display name so rather than using just name we can use tag helpers so we have a label in there we have asp4 tag helper and here you will see all the properties in your model like name you can also add a class if you want but i'll keep it simple what is the advantage of using this tag helper rather than typing just name let me also add a display order here and we'll save this if you go back and refresh there you go not much difference the advantage that this tag helper brings is if we open up our category model right here you can use data annotations to display something else like here if you go back display order is one word what if you want a space in them for that we have data annotations so right here we have display name and here we'll say display order once you do that and if you run the application this time it will use whatever we gave as display name because we are using the tag helper so if you go to create new category now you see a space between so that way inside your model you can define what display name you want and there are many more data annotations which we will take a look in the upcoming videos so now you saw one advantage that you have with the tag helpers that being said we also have tag helpers for input as well so in the input tag here we will use the tag helper which is asp4 this input is for the name and we can give it a class of form control to take full width let's go back and refresh here and great we have a text box let me switch back to the application and do the same for display order if you refresh perfect we have two nice looking text boxes let's also add buttons so we'll go back and here we can do an input of type submit or you can just add a button here then we'll add bootstrap classes btn btn info and width of 100 percent let's call this create and we need a value will be create after that for back button we can add a link here and we can copy the link that we have in index and we'll paste it here when we want to go back we do not need the controller name the action name that we want to go to is the index action to display all the categories and here we can just display back if you save this and refresh great we have create and back and i make this as success and width of 100 so we have two buttons now if you click back it takes you back to the category one thing you notice here is you do not need the category name that name is optional because you are dealing with views in the same category if you had to go to the page or view that belongs to a different controller then you need to explicitly define the controller name here by default it assumes you mean the same controller that you are in right now so with this our page is looking in a good form when we see the add category let's continue in the next video this time what we want is when we enter anything here and hit the create button it should add a new category to database so for that if we go back to our application you can see we have input type of submit and then we have a form here which goes to the post of create so if we go to category controller we need to add that we can copy the get for create paste it here but this time we need a post for create now inside the post right here we will get a category object that we have to add to the database with post what you should do is you have to define that this is actually a post action method so you'll add an attribute http post and we will be using validate anti-forgery token validate anti-forgery token is a built-in mechanism with the forms in which it appends an anti-forgery token and on the post you validate that that token is still valid and the security has not been tampered so we get that built-in security so we'll use that in all of the post action methods now here you will receive the object that you have to add to the database adding to database is simple you need to access the db context db on category you have the add method provided by entity framework core on there you can see it expects a category entity so we'll pass the object and then at this step it will not add the category to database if you want to add it you have to call save changes and then it makes the database call on line 41 once it adds the category what we want to do we can just go back to this index and display all the categories so rather than returning back to a view we want to return redirect to an action method and what action method do we want to redirect to we want to redirect to this index action since it is in the same controller we do not have to define the controller name here let's give this a try and see how things look let's go back and add a debugger right here and let's go to category add a new category we'll try to add this we hit our debugging point and inside the object here you see we have the display order as well as name which is valid how did it automatically bind this and passed it here the reason is if you go to the create you used tag helpers for input since we used asp4 it automatically knew that whatever was being entered in this text box it has to bind that to the name property of the model which is category and on the post it passes that to our controller right here so if you do f10 you execute the add statement if you go back to the database and you execute here it has not been executed if you run the save changes and if you go back now you'll see three records so you can see it actually executes on save changes let's hit continue and now we see the three categories great so with this you can see that how we can create a new category and we implemented the post action method for create everything looks good right now but what if we want some validations let's take a look at that in the next video before we move on to validations let's practice what we have learned so far with an assignment in this assignment i want you to create an application type model in that model we will have two properties id and name we created the category model with more properties so this should be somewhat similar to that once you create the model then you have to push that model to the database so that a table can be created for that model once you are able to successfully create the table inside the database then you should work on creating an application type controller so the name of the controller should be application type and in there you have to implement the index and create functionality that we did with controllers so far so it is exactly following the steps that we did but for a different model so good luck with the assignment and this will give you practice to understand what we have been implementing so far now in this video let's work on the solution for the assignment i hope you were able to do all the three points that were here let's start with the first one in which we have to create the model for application type and push that to the database we'll switch back to the application and in here we'll close everything that we have close all tabs let's go to solution explorer and we have our models right here we can copy the category model and paste it one more time here and we'll change the name to application type we will copy the name and we'll paste it here now we need properties inside the application type which is id and name we do not want the display order you can remove the key data annotation if you want but i'll just leave it here once you add the model you need to add this to database so for that what you have to do is you need to go to data application db context and we need to create a db set for application type we will call this application type and we won't use the plural notation once you save this you have to add the migration so tools nuget package manager we'll go to the console and here let me clear this and we'll add a new migration we'll call this at application type to database great so migration has been added and right here if you see it is adding the two columns id and name and it has a primary key on the id column this looks good let's update the database i'll increase the size here there we go and perfect database has been updated let's go to sql server to validate them we'll refresh here and we have the application type if we expand this we have two columns so perfect our first task from the assignment has been completed in which we had to create the application type model and we had to push that to the database next thing that we have to do is we need to create the application type controller so let's switch back again and we have the controllers i can just copy the category controller and paste it one more time i'll change the name to application type now i hope you did not do the copy and paste and you created from scratch i do not want to spend time there so i'll just make the changes we'll change the names here we need application db context right here this will be of application type and this will be application type as well we'll retrieve the application type object and we'll add that right here sweet so here it will be application type and that looks good final thing that you have to do is you need to add the views as well so what we can do is we'll just go here and we have the views which is category we can just copy this and paste this one more time we'll change the name to application type whoops we have a spreading mistake there there we go and we'll change the create the model will be application type in there we do not need display order we'll remove that everything else looks good in the index we do not need the display order and we do not need the controller only the action name is sufficient and this will be application type great we'll just have the name here and we do not need display order great now let's give this a test we'll go to solution explorer inside layout we need to add another link for application type here so we'll call this application type controller and perfect let's run our application and take a look at if we are able to create any new application type on the nav bar we have application type now we run into an editor here and i think that's in the application type controller we are passing application type list in the index we have category you can see the class is application type so this will be application type as well so you can see if the model here is different then what you pass from the controller you will get an error message then we'll hit the refresh button and this should load perfect we have the category list here so we'll change that to application type list great let's create a new application here also we have the category so inside create for application type we'll change the heading to add application type and refresh let's try to add a new application and great it's working as expected so that was the quick assignment that we did next thing we'll be working again on the category but before we work on the edit or delete functionality for category i want to show you validations that we have to implement in category so let's take a look at that in the next video now in the last video we had some practice with application type let's switch back our focus to category and in here let's add some validation we want a validation that name should be a required field and display order should be greater than zero how do we actually implement those validation now you can always use custom javascript to check what was entered and display alert message but with asp.net cool you get validations right out of the box in order to implement validations we again have data annotations in order to check that out let's switch back to the application and we did not have to rerun it let me stop that what we will do is we'll open up the category model we'll close everything else and we'll open up the category model here we have attributes like key display name similarly we have requirements for validation so on name we just add a required attribute before that property then the display order will make sure that this is required as well and with display order we want it to be greater than zero for that we have range with range you have to define the minimum which is one and what is the maximum so we can just say int dot max value could be the maximum and then for the third property here you can define an error message default editor message if you don't like it you can always provide a custom error message so here we can just display display order for category must be greater than zero once you add this how do you actually implement these validations inside your view let's take a look at that by going to our view so for category we have to create view here we have tag helpers for validation as well what we need to do is on the top here we first need a div and we'll use asp validation summary it has multiple properties all model only and none let's keep it to model only for now and we'll add a class of text danger to display it in red that being said where we have the individual properties in those places let's add a span and in there we have another tag helper asp validation for in this pen we will display if any error messages are for the name property so in here we'll define name here and we'll give it a class of text danger we will copy this and we'll do the same for display order so let me add that here once you do this and if you run the application you won't see the change because you are not right now validating it now validations you can do it on server side or on the client side let me show you first how to do the validations on the server side so server side we have the controller for category so we'll open up the category controller and before we actually add a category we want to validate we already have the validations inside the category model so asp.net core has a method here which is model state dot is valid this actually checks if all of the rules that you have defined in your model are those valid if those are valid only then it will go inside the if condition so only if it is valid we'll paste it to add the new category and return to the index if it is not valid we just want to return back to the view so that we can display the error message now when we return back to the view we can pass the object right here so that we can have those values let's see this in action so let's run the application and let me add a debugger and let me add a debugger once we do that let's continue in the next video now that we have added the debugger let me switch back to the application and let's go to category this time if we try to create a new category and hit it with the empty record you see it goes back and it hits our breakpoint here we have to debug the model state so if we go on model state let's first examine that is valid you can see it's false now what properties are invalid so if you hover on model state expand this go to result view you see both the properties and both of the validations are invalid so if it's invalid you'll continue it will return back to the view and it displays the error message okay so that looks good let's say we add some value here and the display order will make it zero display order if you remember we have validation that it should be greater than zero if you hit create again that is valid is still false this time if you examine what properties are not valid it's only display order the name is now valid so you can see how validations are working and now you see your custom error message that we implemented so with this we saw server side validation if you change this to something valid now and if you try to create it should be successful you can see it was created and we have the same test with display order too now we have the server side validations but what if we want to do the validations on client side to avoid a round trip implementing those is simple as well you will just go back to your create and right here at the end we will add a section for scripts here you can add any of the javascript if you take a look at the solution inside the shared we have validation scripts partial we need to use this inside the section here and it will do the client-side validations automatically so here we will use the tag helper in which we have partial we'll give it a name of underscore validation scripts partial make sure that the name is exactly as you see right here with that in place if you save this and if you refresh the application if you try to hit the create button you see the error message directly here without making a round trip if you go back we still have our debugger in model state that is valid but it doesn't even hit there and it displays the error message as soon as you change it so it's not hitting our server and the validations are being done on client side now so with this we have seen how we can implement client-side validations and server side validations i want to show you one more thing if you switch back to the create in the validation summary we have model only if we make it all and if we go back and refresh the page let's try to hit the create button now you see two things where we have the validation summary it displays all of the error message and then in the model it displays the corresponding so if you have model only in that place it was only displaying the error message where you have the asp validation for so those are the two things that i wanted to show you with all and model only so we'll save it and we'll just use model only even if you comment this line out and if you go back and hit create it still acts the same but i wanted to point out the changes so i added the validation summary but in future just validation for will be sufficient and for client-side we need to include validation scripts partial so that being said we have completed the validations for category now we need to add two more buttons here first button will be to edit a category and the next one will be to delete a category so let me switch back to the application stop it here and we'll go to the category index right here if we scroll down here where we have the td that is empty here we will be adding buttons so we can just add a class of text center here and we'll give a div give it a class of w 75 percent and we'll make it button group we can also add a role of group here and i want to add to anchor tag we have an anchor tag on the top so we can just copy this and paste it right here two times first one here will be for edit and the later one is for deleting a category now we need action names for edit and delete so we'll call them edit as well as delete we have not added these actions but we will do that in a while so we have ptn primary and for delete we'll make it danger to give it a red color now think about whenever we have to edit or delete a category what is one thing that we will need the one thing that will need is the category id that user wants to delete so how will we pass that id when this link will be clicked asp.net core also has a tag helper for that which is asb route hyphen and then you need to pass the id or the name that you want to give to that parameter we will just call it id and here we need to pass the id that we want to retrieve in the action method so that we can access using this obj so we'll pass obj dot we should see all of the properties and we want to pass the id of the category here so we'll copy this and we'll paste it in edit as well with that in place let's run our application and make sure the buttons are displaying we do not have the action so if you click it will just give us an added message so right here we go to category and we have the edit and delete i also want to add some margin here so where we have the classes right here i'll do margin x2 okay and this looks much better so now if you hover on the edit you can see the id is appended in the url and also if you go on delete you will see the same things if you click we have the url but we do not have that page or action method so let's add those action methods in the next video in this video we want to work on category controller and we want to add the edit and delete action now in edit and delete both of them we are passing the id so if we go to category controller we can copy the get for create and paste it right here we'll call it get for edit and we'll call this as edit as well in here we will be receiving an id because that is what we are passing from the asp route id right here so we'll receive an id and based on that id we need to retrieve that category from the database and we need to display that to the user so here we will first check if id is equal equal to now let's make it a nullable field or we can say if id is equal equal to zero if it is any one of these scenarios we will just return back not found because that is invalid if that is not the case we want to retrieve the category from the database now we will be using the db context in there we have category this will retrieve all of the categories but we just want the one category where id matches the id that we receive in the parameter so for that ef code provides a find method in which you need to pass the id here the find method works only on primary key so if you pass the primary key of category it will go through that column and pick a record whose primary key matches what we pass here which is the id after we get that we can check here if object is null this means record was not found and we can return back not found again if it finds the record let's pass the record to the view so that we can display it so this looks good let me add the view we'll go with the razer view and let's add this edit will look exactly similar to what we have for create but the only difference is values will be populated let's go to the create for category copy everything close this and paste it right here rather than action which is create we can just remove this from form the reason i was able to remove that is we are in edit and the post action is also the same name as edit so in that case it is an optional field if it was something else then you should define what action it should post to since it is same we can remove that we did not need the validation summary rather than add we will display edit category here we'll scroll down in the value create we will just display update with that in place let's run this application and give edit a try so we'll go to category we should have two buttons edit and delete let's click on edit great you can see the name as well as display order was populated by default so next thing that we want to do is when we hit this update these values should be updated in the database let's work on that in the next video now we need to implement the update functionality so we'll close the application here and we'll go to category controller we can copy the post action method for create and paste it for edit we'll call this edit and the object that it should receive should be category and we just need to change the name here to edit then when we are adding a category rather than add we should add the update here and then we'll save the changes redirect back and everything looks good now this will work for category but if you have complex object where within category you have other objects and everything here you will face an error the reason is if you go back to your edit right here we are using name and display order so when we'll be posting we'll be getting those two values but what about the id we have not used it anywhere here because of which the id will be zero so what is recommended is right here we'll have an input field we'll use asp4 which is the id and then we'll have it in a hidden field that way when we post the form in the object we have the id as well the update will only work if there is an id associated because based on that it finds out which entity or which category it has to update in the database that being said let's run this application and give that a try so if we go to category and if we try to edit the test with display order one two five five five update great you can see it has been updated successfully also in edit if you remove this and hit update we get the error message and everything is working as expected last thing that is remaining is the delete functionality let's take a look at that in the next video now what we want to work on is the delete functionality so the delete page will look somewhat similar to edit page the difference is these things will not be editable at all and will have a delete button so let's go back to our application and we can copy the edit we'll paste it for delete in delete as well we are getting the id that user wants to delete so we'll call this delete and this will be delete as well now with delete we do not want the complete object all we care about is the id so we are just getting the id and that should do the trick but when we do that we get some other error message with the delete the reason is we have two methods here with the same parameters previously we had the category object so this was fine how do we fix this we can change the name to something like delete confirmed or delete host but in the view we want the name as delete and that will take care of this error that being said rather than update we will have to use the remove method on there but we need the object so we can retrieve that object using this method here we'll paste it here and we'll find it based on the id pass it to remove save the changes redirect back to action this looks good for the delete post and delete cat will be exactly same as edit get because we need to retrieve the category and pass it to the view now with delete we don't care about the model state because there won't be validation the only check if you want to add is the object if this is null then we do not have anything to delete and we'll just return not found else we'll just remove the entity that we found and redirect back to the index action so this looks good next we need to add the view so inside category we can copy the edit and paste it one more time we'll call this delete and the model will be same rather than edit category this will be delete category then we want to display the name but we do not need any validations and we'll make them disabled so the user cannot edit them with the button we'll call this as delete and the class will be danger to display a red color perfect so everything looks good let's run this and give this a try once we know the basic foundations of one crud operations now you will see the pattern and everything will start to make much more sense when we go to category let's try to delete as soon as you try to hit the delete button nothing happens what is the reason the reason is simple right here if we go to the controller the name is delete post so what you can do is we'll copy this and we can go to the delete.cs.html in the form method we can write the asp action and we can say delete post since it is not the same name as delete you do that you refresh the application and you hit the delete button it works now so you can see one workaround when the action name is not same you can explicitly specify what action should be called on the post action method for this form so with this we have completed the crud operations on category now that we have completed the grud operations on category i want to add font awesome in my website so we'll go to font awesome here here we have the font awesome let's go there and let's hit on the start and we'll get started here we'll hit the download and the download begins once it finishes we'll open this up and extract it so i'll extract this and we'll close it here we'll go to our snippets folder because that is where i extracted and we have the font awesome right here what i will do is i will copy everything that we have here and we'll switch back to our solution we'll right click on ww root folder and open in folder explorer here what i will do is i'll add a new folder for font awesome and i paste everything that we copied great so we have copied everything here how do we use font awesome now using that is simple we'll just go back and we have to add that in underscore layout we have the css here we'll add a link rel of stylesheet and we'll add an href up will point to the css here the intellisense is not working let me stop the application and we will add that path so right here inside ww root we have font awesome css and all dot css let me pin this with that in place font awesome is added to our website now how do we use the icons let's run the application and see we don't see any error message and next thing we'll start using the icons we'll go to category and let me add a plus sign right here with the create new category so we'll go to the index and let me go to font awesome again and we'll search for plus sign [Music] you go here and you'll copy this will go back in the index where we have create we'll paste it and we'll add a space we'll save that go back and refresh not this there we go this should add a plus sign right here great you can see font awesome is working let me add icons for edit and delete so if we go here and if we search for edit we have the first icon i'll just use that copy it go back to the application we'll paste it here and then we'll do the delete icon copy this and just paste it right here next i won't go back i'll just use the sign out icon for that we'll copy this and we'll go back to edit we have the back right here we'll paste it i'll do the same in delete as well and we have to create so let me go to the views we have to create and we'll scroll down let's go back to the application and see if everything now looks good great we have edit and delete and then if we go on create new we have the back icon and perfect everything looks good now here rather than displaying edit delete and everything i'll just have the icon and i'll remove the text this is self-explanatory so we'll leave it at that so with this we have completed adding font awesome to our project and all the crud operations with the category is working next it's time to replicate the pending things that we have for application type in the next assignment things are moving along great and we are making good progress next thing for our assignment is we need to add the required validation for the application type name and we want to do that on both client side and server side along with that we need to perform edit and delete functionality with application type this is exactly what we did with category so you should not face any issue so good luck with the assignment and in the next video i'll do the same to provide the solution so we need to do two functionalities first we need to add the validation so let me switch back and we need to work with application type model so right here we need to add the required and that will take care of making it a required property once you make this change then we need to add the validation summary so we'll close everything that we have here we'll save this and close it as well now we need to open up the category for create and we have the validation for we can just copy this we'll go back inside our application type we have create we'll paste it right after the input tag if you open up the create here and if you just copy everything that you see here and we'll just paste it we'll make sure this is for application type right here changing things will be much simple we just need application type add application type name looks good we do not want the display order and buttons looks good yep so everything is looking good right here next thing is we want to also modify the index for application type so we can just copy things that we have inside this td we'll go back here and we'll paste it right here the controller name you can either change this to application type or you can remove it because it is within the same controller once you do that changes inside the index it's time to go to the controller for application type and category here we will be dealing with only create but in future we have to perform edit and delete as well so why not just copy everything that we have in category controller we'll copy this paste it inside the application type controller right here we'll scroll up we'll copy the name application type controller and we'll just delete this we'll paste it here there we go and we'll change to application type we can change things one by one but rather than doing that i would prefer doing the bulk change there we go so what we did is we updated everything that we did for category with application type if we build our project we shouldn't see any error message now we have also added model state inside the post so let's give that a try one last thing we'll close the index in the create is if we go to the create for category and application type we have the validation scripts partial for the client-side validation so let's give that a try and see if our validations are working an application type will create and create it's working if we try to edit this the edit view was not found so let's add edit view and delete view and we'll add a plus sign on the index so we go to the index of category we have the plus sign here we'll copy that and we'll paste that in the index for application type next we want to edit and delete we can copy these paste it inside the application type and we'll modify them first thing will be the model which is application type and we do not want the display order i believe that's all that we had to change the action name is delete post and we have the delete post and application type yep we double check that next we have the edit so we'll change that to application type edit application type and we do not need the display order this looks good in delete we'll change it to delete application type let's run our application and with this everything should be done for our assignment now again i have been copying and pasting everything but i hope you do these things from scratch so that you get more exposure to what we just did let's try to edit this and that's working if we delete great everything is working as expected all the grud operations are working now with all the validations if you are interested in the full course you can view the details on dotnetmastery.com but i do not like to leave things at this i want to show you one important step in any web application which is deployment right now our application is a basic grud web application but still we can deploy our application so in order to do that we'll have to go to azure portal here you can sign up for your account you can get a free account for 12 months i already have my account so i will log in and rather than sign up it will show me i already have an existing subscription so i'll log in there and we are on our portal you can see i have 200 dollars of remaining credit that you get when you sign up for the first time in here whenever you have to deploy anything you create a resource group then in that resource group we will have to create an app service to host our website and we will need a database to actually insert all of the data we can do everything in the portal or we can switch back to visual studio and in here if we go on rocky let's right click here and we will select publish that will show us all the options that we have to configure we will select azure here we'll select the windows service then you have to make sure you sign in to your account if you are not signed in so in here we will be creating a new azure app service i'll call the application name as rocky crud and i already have an azure subscription which is the free subscription then we have to select the resource group if you are here for the first time you will just have to create a new resource group and you'll have to provide a name i already have a group so i will use that after that we need to select the hosting plan we can create a new hosting plan here and i'll call this rocky crud plan for size i will use the free one we will create this and that will configure in the existing resource group for my case it will create a new hosting plan for our crud application we'll wait for it to get done once it completes in here you see deployment slots we are not working with slots but in production application if you have multiple feature sites you can use deployment slots here let's click finish and once you do that it will show you some of the service dependencies like it says sql server database so we will configure the sql server database right here we will select the azure sql database and we'll create a new sql database i'll call the name as rocky quad db and we can select any of the existing server or i can always create a new server will keep the default location and for the admin username you cannot use admin so i'll use admin user and password i'm gonna use admin one 123 star with a capital a so we'll use that and we will create a new sql database so with database we had to create a database server and then we had to create the database resource group can be common for both of the database as well as app service so great this looks good let's hit next here and we need to configure the connection string name how do we want to save the connection string we will go with the none option i do not want to configure these things we already know the username is admin user and password is admin 123 star once you do that we have the complete connection string right here so make sure you copy this we will hit the finish button that will configure the dependencies and will hit the close once it is done so you can see sql server has been configured next we will edit the deployment mode here and we need to change the connection string if you expand the database here you see the connection string we will remove this and we will paste the connection string that we copied we'll select the checkbox to use this connection string at runtime on top of that with entity framework core migrations if you scroll down we will paste our connection string here again and we will say apply migrations on publish that way if there are any pending migrations they will be applied right now the.net 5 is in preview version so we will have to change the deployment mode from framework dependent to self-contained if you do not make that change your application will not work once we make all of these changes let's hit the publish we have the site url right here so once it publishes it will automatically open up this url and we will see how things look in azure great so you can see application has been deployed and you see the url that is on azure if you go on category and in here we can create a new category let me try to create one category with display order and great you can see it works all the migrations were applied automatically and we did not have to do anything so with that the free course comes to an end but there is much more to learn when it comes to asp.net core mvc i have full course which is divided in two parts on dotnetmastery.com in the first part we will cover more topics on displaying all the products and placing inquiry then in the second part we will focus more on architecture of our application and we will build the complete order management in our website you can find all the details on dotnetmastery.com so good luck and i hope to see you guys in the detailed courses
Info
Channel: freeCodeCamp.org
Views: 437,211
Rating: undefined out of 5
Keywords:
Id: Pi46L7UYP8I
Channel Id: undefined
Length: 148min 1sec (8881 seconds)
Published: Thu Aug 20 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.