Full Course - Learn ASP.NET Core MVC in .NET 8 | CRUD Operations | EntityFramework Core

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this course we are going to learn ASP core MVC by creating a supermarket management system in Don 8 and technologies that we are going to use to create the application are ASP MBC which is our Focus Ed framework core SLE server and ASP core identity to secure the application you will need to know a little bit c and a little bit s server before you can take this course but the rest of the technologies will be covered in this course while I'm creating the application so this course is focused on practice and creating the project you are going to learn all of these Concepts while you're creating the application so if you have learned all these Technologies before but you need a project for you to practice then this is very good course for you if you haven't learned MBC any framew core or speed onite core identity don't worry about it all these Concepts like I said before will be covered in this course while you're creating the application with me let's take a look at the application that we are going to create with SB MVC in don8 we are creating a supermarket management system if by loging as a user so tester number one is inventory manager I can log in as inventory manager and then I can manage categories I can manage products of course for managing categories and products we can create read update and delete so all of the crow operations as well as different ways of data validations are including in here we can also check transaction but I cannot actually access the Cashers console over here now if I log out and log back in with tester number two which is a cashier now I cannot access categories products because these are Inventory management but I can go to the Cashers console I can see my name displayed over here and and then I can sell any product that I want to sell for example if I want to sell some uh White brand and I want to sell let's say someone comes to me buy five of them and I click on submit button I'm selling the white bride and today I can see the quantity before and quantity after the quantity sold and the total amount uh I can also go to transactions and take a look at all of the transactions that is sold today I can also print transactions and now printing to PDF and click on Save so this is basically just a export and click on Save again now let's go to the folder and take a look at our printout and we have a beautiful report but you can see that this is not just prod applications right this is a fairly complicated application where you can dynamically run partial views and also for transactions I'm using view component so so you will have a lot of stuff to learn in this course now let's take a look at our curriculum so in section number one we are going to learn learn some basic concepts of MVC and some basic techniques to prepare us to work on Section number two which is the categories CR operations you can see that while we are creating the CR operations we're going to learn about many techniques we're moving on to implement products crowd operations so this is considered a course project you are expected to implement everything by yourself with some help from the first lecture moving on to section number four we are going to implement cashier's console where a lot of dynamic stuff is introduced so we're going to render partial view with jQuery we're going to use CSS to highlight product and then we have many other assignments included in this section in section number five we're adopting clean architecture so before section number five we're using static repositories to contact IM memory database so here we are preparing a use case driven plug-in based architecture which is going to help you to build larger applications although this application is a small application but it's good to learn some good architecture to help you to build Enterprise level applications moving on to section number six using n framework core and SQL Server we're going to create a SQL Server data store plugin thanks to our clean architecture we can just create a plugin and automatically the application is going to talk to secr server in the last section we use identity to protect our application and we're going to learn about policy based authorization to protect our application with different permission levels okay we have a lot to learn in this application I hope to see you in the course ASP core MBC application framework is a traditional web application framework in this video let's try to understand how a traditional web application framework Works what are the essential things that a traditional web application framework has has to do let's get started a web application always has a client which is usually a browser and a server when the user needs to access anything in the web application it interacts with the browser and then the browser will send a request to the server to request the web page that is needed the server will process that request and return that back to the browser it is as simple as that it is built on request and response model BR sends a request to the server the server returns a response any framework that is based on this type of request and response model needs to do the following three things first when the server received the request the framework will have to map the request to a function or method to process the request so the first step is mapping the second thing that it has to do is that it will have to let the function handle the request and generate the HTML and the third thing that it has to do is to return this generated HTML through the response to the BR so return HTML therefore these are the three things that a traditional web application framework has to do in this video let's try to understand why we need a framework by creating a spon qu application without a framework and see how it works and what problem it has so we can understand why we need a framework like as. core and VC let's start by creating a project by the way I'm using vual Studio 2022 preview Edition so that I have access to 8 so go to new project in the search bar type in Sp core and if you scroll down you can see this asp.net core empty choose this option click on the next button and let's name this solution MVC course and project name web application click on next and choose the latest framework by the time you use it you might be already seeing the released version of Don 8 I'm currently using Don 8 with preview 7 clicking on create keeping everything as default application is created and if we go to our solution Explorer you can see this program. CS file so this looks like it's a console applic apption right so if you create a console application you also have a program. cile so you can consider this is a console application is actually runs as a console application if we run it let's see what's happening you can see the console application is running right over here and it is listen to this on this port right it's also listening to another one and the constant root folder is this folder we just created and you can see the hollow World content here basically the browser is sending a request to request a web page from this location and first thing that this application does is that it Maps the root URL to this function basically this is a function and this function doesn't have any parameter if you have any parameter it will go over here and the function returns a string which is hello Ro right so this is the first thing that it does right it Maps the request to this function secondly this function process the request by simply return the string thirdly this string is returned as part of the HTTP response to the browser and it renders on the browser as we mentioned in the previous video a traditional web application framework should do the three things mapping handle the request return to HTML you can see that that even this simple application already does all those three things of course except that you know it's not actually returning HTML it's returning a simple string but we can modify this to actually return a HTML I happen to have the code created I have a helper function to help me to write HTML I'm going to paste it over here you can see that this right HTML function it takes the HTTP context takes the HTML and then it uses the response object to write the HTML out so if we want to write some HTML we can first of all pass in the context object right so basically this is a type of dependency injection we will talk about it later but the context can be passed like this and then we can implement the function to write the HTML so first of all we can write very simple HTML like this and we put our Hollow world inside here this time it will be header one and then we can add a line break here and we can say welcome to this new world we close our body and close the HTML document okay once I have the HTML forgot to name the variable here we can then call the helper function to write the HML let's pass in the context and then pass in the HTML string let's give it a try run the application again and now you can see that our HTML is beautifully rendered on the browser we can even make it a lot more complicated and I have prepared some code here I'm going to copy and paste it over here and then we will go through the codes okay now I have two map first and map the get request to this document and you can you can see that this is actually a HTML form and it has user and password so this is actually a simple login form and then there this Maps a HTTP post request so basically when the submit button is clicked on this form is posted back to this particular URL and this map post function actually Maps this request to this particular function and this particular function first of all get the username a password it verifies username password if it verifies successfully then it shows Welcome to our simple framework otherwise it spit out the same URL that is spit out in this G function allowing the user to log in again with the same form so let's give it a try now you can see the username password and if I type in Frank and if I type typ in a wrong password click on login it says login failed why it says login failed you can see that in the else statement here we have a label and it says login failed okay so if I enter the correct password which is password click on login now it says Welcome to our simple framework but this type of simple framework has lot of problems first of all you can see that we have to analyze the request and get parameters out which is the data that we need to work with and secondly the HTML is in a strin and it's very hard to work with it's very hard to manipulate thirdly the logic here and the view which is the HTML are all mixed together and then you can see that validation is done completely manually there isn't a mechanism for developers to do it otherwise the business logic here is also mixed up with the HTML which is the view so in a word everything is extremely tightly coupled basically you just have to do everything in this function ideally we need a framework that provides separation of concerns where we have a dedicated functionality to getting parameters we have a dedicated functionality for doing validations we have a dedicated functionality to work with HTML we have dedicated place to work with authentication and authorization so everything has its own place to implement so that we don't have to put everything together and work with this one single function so that's where MVC comes to rescue and we are going to cover how MVC Works starting from next video I will see you in the next one in this video let's talk about how MVC works in the context of a ASP core web application when a user request a resource from the browser the browser sends a request to the server after the server received the request when we use MVC the first thing it does is that it would root the request to the controller right because MVC stands for model view and controller here the request is directed to the controller the controller is nothing but instance of a class it plays a role of a coordinator here when the controller receives the request it starts processing the request by calling some other components that implements the business logic where that component is we don't have to worry about right now but the end result is that the data that is needed will be loaded in some something that is called model in most cases a model is also an instance of a class and right now this instance of class is hosting the data that needs to be displayed on the page the next thing that the controller does is that it fees the model to the view the view basically contains a HTML template so the controller fees the model which is the data to the HTML template and then combines the data and the template together to generate the final HTML afterwards the view is returned back by the controller to the browser as part of the HTTP response so to summarize ASP Maps the request to the controller the controller acts as a coordinator it loads the data into the model and then feed the model to The View when data and the view templates are combined together the final HTML is generated and then the HTML is returned as part of the response to the browser and the browser renders the HTML after that the user sees final page so that's how model view controller Works within the context of as. web application and here you can see that the view is the place where the UI representation and logic is handled the model is where data is populated the controller is the coordinator everything has its own place all of the responsibilities are separated and this is following the principle of separation of concerns different things are taken care of by different components in the framework for developer our main goal is to focus on implementing the business logic and typically the business logic is implemented in different other components so I'm going to say application logic and controller class basically invokes the application Logic the data is then populated into the model so let me remove the application logic let's keep this picture focused on the MVC pattern hope everything is clear for you if you have any questions please feel free to ask if otherwise I'll see you in the next video we know a lot about the MVC pattern in ASP donate core from the previous video in this video let's go ahead head and add the support for MVC framework in our application here so first of all let's delete all of these functions that we added in the previous videos delete this one as well so this is minimum code in as D core web applications in order to add support for MVC framework first of all we need to add the routing capabilities the routing capabilities is what is needed for redirect the request to proper controllers and also the method in the controller right it Maps the request to the to the method inside the controller which we will create in the next video but in this video in order to enable MVC framework we will need to add the routing middleware to do that we can say app. use routing so after that we will also need to add another one and that's called map controller root and I'm going to copy and paste what needs to be done here then later we will explain how this actually works basically this is the pattern of the URL that this mapping method understand and as long as you have a URL pattern like this it's going to be able to map the HTTP request to the particular controller action method we will cover this in detail later with the this map controller rout method added another thing that is needed is we need to dependency inject all of the dependent Services that's required by this method right so this method itself it requires a lot of services which we will need to inject into ASB otherwise this method will not work correctly in order to do that we're going to say Builder doservices so this is Services is a collection of services we just need to add the services that required by this method into the services collection fortunately it's be done like what already have a extension method it's called add controllers with views if I hover my mouse over it you can see that this is a extension method it says over here this extension method helps to inject all of the services required by this method into the services collection in a speedon core so with all of these three things added the rooting middleware the map controller root method and the dependence injection to support controllers with views which is required by this method our MVC support is added now that we have the support for MVC framework added in our ASP program.cs file in this video let's add a controller in order to to handle the request as you can see our controller is the first thing that meets the request so let's go ahead and add a controller so there could be many controllers in any applications so therefore the convention is to create a folder that is called controllers and then we can add our controller over here so right click and add controller here we can add a empty controller click on ADD and we can just keep the name as this just call it home controller and click on ADD again now you can see that we have our home controller class created derived from controller Base Class the space class comes from the SP sp. core MVC Nam space and it has a default method created which is called index a public method enter a controller is usually called a action method any action method is used to handle request when a request comes into to the server it will be mapped to one of the controller's action methods so in this case we have this index action method so how do we map a request to this particular action method if we go to our program.cs file you can see that we have a mapping pattern here this means that if we provide a URL that follows this pattern then the first part it refers to the name of the controller the second part it refers to the name of the action method and the third part is optional if it is provided then it refers to the parameter of the action method so in this case we have a home controller so the name of the controller is home and the name of the action method is index so therefore the URL pattern to map to this particular action method is slome SL index let's simplify this action method to return a string just like before and I'm going to say hello world from action method and let's give it a try so if I go to slome SL index and then hit enter Then you can see that this hello world from action method is displayed here in fact if we remove the URL pattern here and just load from the root we can still hit the same page Why is that let's go back to the program. CIS file and observe this pattern once again so you can see that this part refers to the controller this part refers to the action but both of them has a default value which means that if we don't specify this part then the controller is the home controller if we don't specify this part then the action method is the index action method and we happen to have a home controller which corresponds to this and we happen to have a index method which corresponds to this index method so therefore if we don't specify any URL then still this action method is triggered and the hollow word from action method string is returned if I create another action method and let's just call it error and let it just return a string I have an error here in order to let this action method to handle the request and return the string we can just run the application and then specify slome slash error and then you can see I have an error here so therefore we can say that a controller is basically just a grouping of different action methods it is the action method that hand know to request so if we look at our first diagram over here any traditional web location Frameworks will need to do these three different things mapping to a particular function and then the function handles the request that's the first and the second tasks in our MVC application framework we are able to map the request by using this setup and a specified the mapping pattern over here that accomplishes the first task and also we have the action methods that can handle a HTTP request and that accomplishes the second task okay that's everything I want to cover in this video I will see you in the next one in the previous videos we have used the root middleware and the map controller root method help us to do task number one which is Ming and we have used the action method to handle the request now it's time to return the HTML so let's go to our code and over here and let's look at our controllers here so currently we're only returning strings we're not actually returning HTML let me first of all delete this ER parer we're not going to use it let's actually start adding views there are many ways to add a view you can add it manually but there's a simple way to add it which is by right clicking on the action method and then click on ADD view let's add a empty reader View and let's make sure that the name of the view corresponds to the name of the action method and then click on ADD now you can notice that a views folder is just created and then a home folder is created after that index. cshtml file is created just like by convention a controller's folder should contain all of the controllers a views folder should contain all of the views and then you will have another subfolder here that corresponds to the name of the controller so in this case we have the home controller so therefore video Studio automatically created this home folder and under that it created this index. CSH HTML file any file that ends with CSH HTML is considered a reader view file and the name of this file is name as index that corresponds to the action meod inside our controller over here now we can add HTML inside the view so we can start with very simple HTML I just because I just want to demonstrate how this works so we can add just like before like welcome to homepage add a line break and then add some descriptions here this is our new home after that let's go back to our controll over here you can see that this is still returning a string we want to return the HTML that is defined in this Reser view template over here so how do we do that we can change this return type to I action result and then we can change this to use the view method and that's it so let's give it a try you can see that HTML is being displayed in our homepage so how does this controller know which view to return without actually specifying but this is all by convention just like I mentioned just now that we have this home controller corresponds to this home folder we have the index method corresponds to this name of this View file by convention if we don't specify the name of the view then it's going to look for the view name that corresponds to the action meod name in this case we do have one over here therefore espon chord Returns the HTML inside this file however you can specify the name of the view so inside this method here you can see that has different signatures the third one has a view name over here so we can specify the view name like this index and then if we run the application again it will still show the index HTML template and if I change this to let's say index one then we have to change this to index one so this will still make the application work as you can see the page is still loaded however in this case we delete name of the view then then it won't work because it's going to try to find a Reser view file that has the index name this file currently changed to index one therefore it's not going to work if we try to run it then it's going to complain and error message is very informative you can see that it's looking for the view index inside the following locations and it cannot find it so let's change this back to index now if we run it again we will be able to see the same homepage and let's go back to our controller now you can see that we're returning ey action result but our method here returns a view result so what is the relationship between ey action result and a view result so by looking at this name you can tell that this is interface that represents the return type for any action method right because the name is action result and there are a lot of different result types in this case the view method here returns a view result and if we go to take a look at the definition of the view method here and then if we go to the definition of the view result you can see that the view result derives from the action result and then if we go further the definition of the action result class it actually implements is the I action result let's come back so any action method can return ey action result because this is basically a abstract of all of the possible return types because all possible return types implement this interface so you can always use I action result as the return type but inside the function you are going to return a specific action result that actually implements this interface so the main purpose of this video is to show you how to create a view and how to return the view just like this and then your HTML goes into the Reser viiew file over here inside the reserv viw file you can see that you're really dealing with real HTML it's no longer just string like what we did before right so this more manageable easier to program with now in this course we are going to create a supermarket management system where we have different products to sell in the supermarket each product belongs to a category for example different drinks belongs to the category of Beverage vegetables would be belong to the category of vegetable so therefore I want to create a categories page that shows a list of categories which is going to serve as the starting location for managing categories so therefore before we finish this video let's use what we learned to create the categories page and for that we can start by creating the controller so let's add a new controller and let's add a empty controller and let's name the controller categories and usually what it suggested is that we use plural form of English word right so instead of category controller we say categories controller and then over here we have this index action method and now what we need to do is to add a view right we're not displaying data yet we just created a static view first so right click on the index action method click on ADD View and then click on ADD here just make sure that this name corresponds to the action method name and then you notice that this categories folder is just created and this view is created I'm going to copy what we have over here and paste it in the categories index page and here I'm going to say categories and I don't want to use H1 I want to use H3 and here I'm just going to say we are going to display categories here so I'm not going to display it yet we are going to follow through the lessons and eventually categories will be displayed over here and if we run this application right now can you tell me how to navigate to categories page so we're going to do categories which is the name of the controller and then we're going to do index which is the name of the action method and I'm going to hit enter right now and you can see categories and we are going going to display categories over here so let me magnify this you can see it clearly another way to load this page is by not specifying the action method because by default if you don't specify it index action method will be triggered so you can see that I can still see the page okay that's everything I want to cover in this video and I will see you in the next one in this video let's talk about passing parameters to action matters it's the previous video we started creating this categories page and at that time we're seeing that we are going to display the categories right here so instead of actually use data to display the categories let's start by hardcoding different categories here so let me change this to an ordered list and then I'm going to have a couple of list items here what I want to do is I want to show two different categories when the user clicks on the category it goes to the added category page so for that I can use a anchor Tab and the first category I want to show perhaps is beverage and the second category maybe just meet so what the URL should be let's go back to program.cs and look at this pattern over here so we have controller we have action and then it has a optional parameter over here this parameter when specified will become a parameter of the action method so we can take advantage of this URL pattern and let's go back to index. CSH HTML over here and we can say slash categories slash edit edit is the action that I want to do because when the user click on the beverage the user wants to be able to addit the beverage category so here I just want to hard code the ID of this category for now I'm hardcoding number one and then the ID of meat is number two so since this kind of URL pattern can be already taken care of by the map controller root method we just need to create a controller action method that corresponds to this URL pattern that is specified over here right which the controller name action method name and a parameter so let's go to categories controller here and let's add another action method as I mentioned the return type you can always use I action result the name of the method should be added the parameter should corresponds to the pattern so in this case it's going to be integer and I'm just going to say ID I want to just show this ID on the page so instead of returning a view I can use a different result that is called content result again this content result actually implements this I action result interface to prove I can just go to the definition and you can see that it derived from action result and of course action result itself implements the I action result interface so the content result has a property that's called content I can assign a string to it so I'm going to say ID do2 string now in the categories page I have two links that goes to category number one and category number two and then in the controllers I expecting those links will be mapped to this action method and then eventually the ID of the category will be displayed on the page so let's give it a try okay let's navigate to the categories page first and we see the beverage and meet so let's click on the first one which is beverage and then you can see number one rendered on the screen if I go back and click on meet we see number two rendered on the screen let's take this moment and look at this URL over here so of course if I put 222 it should display just 222 so what if I put ABC over here and you can see that it sets this to zero why does it show zero over here so let's go back to the code over here you can see that this is integer and the default value of the integer is zero so s SP done core does not actually throw exception when the mapping from the URL to the parameter fails it actually provides a default value and in fact is smart enough to know that whether this is integer or not right I can use string as the parameter type of course in this case is able to display the string value but if I use integers and then change this to integer it will be able to tell that that a integer is provided and just automatically convert that to integer so then what if zero is a valid value for ID in that case we can use optional parameters like this and then we can use a if statement we can say that if ID has value then we're going to do this otherwise we can say no cont so let's run the application again if I use 1 two 3 it shows 1 2 3 if I change this to ABC then it shows null content because it's not able to actually convert ABC into integer therefore esonic core provides a default value for this nullable integer and the default value for nullable inte of course it's null so therefore it falls into this branch and displays null content string on the page and what happens if I don't provide the parameter at all so I hit enter you can see null content is also displayed and that's because this parameter is not provided so it is supposed to be null and it again falls into this Branch so we have seen that the parameter is passed as part of the URL like this another way to pass the parameter is to use sare string so here we can use question mark with the beginning of the qu string and then we can say ID so this name ID corresponds to the parameter name and then we can say 555 if I hit enter 555 is being displayed so SP spon core is smart enough to map both URL and quer string to action meod parameters we just need to make sure that the query String's name corresponds to the name of the parameter and then the value will be automatically assigned to the parameter of course here it's going to follow the same pattern if we use something that cannot be converted into that particular type of the parameter then it's going to just assign a default value for the parameter that's everything I want to cover in this video and I will see you in the next one so far we have worked with the controller and we have worked with the view but other than passing the parameters to the controller action methods we have never truly worked with the model yet so as I mentioned while we discussing the MVC pattern here the model is what we use to host the data in other words the data is loaded into the model and then the model will be combined to The View and then eventually the rendered HTML will be passed back to the controller and then the controller relay that HTML through the response to be rendered onto the Brader so in this video let's talk about the model let's jump back to visual studio and let's start by creating a model class in the previous video we worked on this editing category so I want to create a category model class to represent a category for that I'll start with creating a folder and I'm going to call that models this this is the convention the controllers goes through the controllers folder the model go into the models folder and the views go to the Views folder by looking at theb application you know this is a MVC application which has a models folder a views folder and a controllers folder so right click on it add a class so a model is simply just a C class we can call it category and here inside the category class I want to have three different properties the category ID the name and the description here here we see the green squeaky lines this is because this is after Donna 6 I'm using Donna 8 and by default the application is set to nullable enabled so therefore we can initialize the strings to use empty strings earless sometimes we accept not values for the properties then we can use a question mark here to just recognize that as developer I know sometimes the value of the property can be n but in this case we can initialize with mt string now after I Define the model class here I can create the view so let's go to the controllers and let's right click on it and add the view add empty View and let's make sure that name of the view corresponds to the name of the action and now the added view is created under the categories folder here here we need to populate it with HTML uh so let's go ahead and populate this with HTML and let's remove the content of the body we know that we created this model class and we know that eventually this model class will be combined with the HTML template that is defined in the view so therefore we can provide a type here by saying model category so when I do this I'm basically just saying that the type of the class that will eventually be combined with the HTML template here is of the type category I can import name space and then you can see the category class name is carer coded and now I can use this in the HTML template so for example I can give it a title here and I'm going to say category and then I provide the category ID so the way to do that is to use add sign and then say model so this model model is a instance of category right so it's instance it's not a type anymore so therefore I can access the properties in it you can see I have a name right I have a description and I have category ID here so all I want in this video is I'm just going to display the title with the ID like this so now let's go to the controllers here so when the request is rooted to this particular action method ID is provided here right now we are just directly displaying the ID on the page so since we created The View we can use the view but we want to combine the model and the view together so what we're going to do is to create an instance of the model first so I'm going to say category equals new category and the ID is ID and here I'm going to say if it has a value then I'm going to use id. value otherwise I'm just going to initialize it with zero and then in order to pass this category to the view right remember that we need to combine the model with the view so we need to pass this to the view so the way to do it is to use this view method and there are different signatures right the second signature has this model parameter third one has the view name and the fourth one has both the view name and the model so in this case because our action method corresponds to the name of the view so we don't have to specify the view name but we can use a second signature to just provide the instance of the model class and because the type of this object corresponds to the type that is defined in the view the data can be then pass into here and then pull out from here okay let's give it a try looking at the homepage so let's navigate categories page now let's click on the beverage link here and go to the category number one and you can see category number one is displayed and let's go to category number two which is meet and you can see that number two is displayed right here so the key things that we learn in this video is that first that we need to create the model class which is just a regular C class and secondly we want to specify the model Class Type in the view and then we can just use it to display the members of the class and next thing we need to pay attention is we want to pass the model instance into the view method which in turn pass this data into the view eventually the data will be displayed in the view so that's everything I want to cover in this video and I'll see you in the next one in the first section of our course we have covered mapping request to controller action method return response from controller action method to the Brader we have also covered defining a model populate the model with data feed that data into the view and then eventually the controller Returns the view as HTML to the Brer to render the page since we have covered the three essential parts of MVC we will need to put that knowledge into use in this section by implementing our categories Crow operations which is create read update and delete and of course in the process I'm going to cover some other aspects of MBC framework let's get started from the next video before we go ahead and Implement our categories quow operations let's take care of the layout of our views because so far we have created three different View files and in each one of them we have full HTML markup and usually in application we may only have one or maybe two different layout right usually just one layout and every page follows the same layout therefore if we have a way to extract the full HTML out and let each one of these view page for focus on what this particular view needs to present that would be ideal espon core MBC provides this type of functionality and that is called a layout file so let's go ahead and create a layout file inside the view folders the convention is to put the layout file in the subfolder and the name of that folder should be shared and then we can put our layout file into the share folder a layout file is nothing but another type of Reser view file so just select reader viw empty of course you can go here to SCU fold everything but let's learn everything from scratch so just create an empty View and here we can put an underscore here and let's call it ncore layout the underscore here it's not anything special it just tells us that this is a layout file instead of a normal view file and in here you can just enter your your HTML layout the way you want it at this moment I just want to have a simple HTML layout like this it has a header area where we can see the title is Supermarket management and then I have the body right now it's empty I have the div and inside the div is where I want to render the content from each one of these actual View files okay so everything specified in The View files comes here so how do I do that I can say add render body this special method here takes the content from The View file and render that in here so basically this is a placeholder for each one of those individual views so with this layout file specified here let's go to each one of those View files that we have implemented so far and we need to specify that this new layout file is layout of this particular view so how do we do that can use a code block erazor syntax code block with ADD sign and Cur Braes and here I can say layout this layout is a string and I can just specify the name of the layout just like this so with this specified I can remove the HTML and just provide the content that I want to have for this particular view in this case I'm just showing the title and the category ID and following the same idea I can go to other views so here I just want to show the categories title and beverage and meat so I'm removing the HTML and its body and of course I'm specifying the layout file for this particular View and now last but not least we have this homepage and following the same pattern we're removing the HTML and then we specify our layout so when we have this the expectation is the content of the view will be rendered in the body of the layout so where is the body of the layout let's go to the layout file here here is the body of the layout you can consider this as the placeholder of the actual View and then this function is used to render the content of each one of these views into this placeholder so let's give it a try let's run the application all right you can see see the homepage works the same way as before let's go to categories page and you can see the categories page also displays the same information as before although the HTML tag has been removed click on the beverage I can go to the category Number One clicking on meet and go to category number two so everything is working just as before so that means our layout file is actually being picked up by the view everything seems to be fine there's only just one problem here if we use this approach that means for every single view we have to remember to specify the layout on the top and sometimes we may forget to solve that problem we can add a view start file so again we're going to add a view which is empty View and then let's name it andore view start so this file has to have this name so this is Convention of MVC is Spore MVC so clicking on ADD and then we can clear everything here all we want to code here is what we have put under each one of these so we can remove this and then put this over here so with this file present over here in the solution we can delete all of these right we don't need to worry about specifying layout in each one of the views and let's try again run the application now you can see just as before our pages are still being rendered properly so how does this work before a view is rendered this view start file is actually executed so when it's executed it specifies layout of this particular view right and then when we navigate to the categories page and we see attempts to render this View and before this view is rendered again this ncore view start special reader page is executed and is specify the layout for this view so therefore we can say that this special ncore view start. cshtml file is automatically executed before rendering any views so therefore we can centralize some logic in here right now we're just using that to specify the layout file of course you can use it for other purposes but for now we're using it for layout file that's everything I want to cover in this video and I'll see you in the next one right now if we look at our page here it's very plain we haven't applied any CSS styles to our Pages yet so in this video let's try to enable static file middleware to support the use of static files like images scripts or css files in our application in our application we want to use bootstrap to sty our application so therefore I have gone to get bootstrap.css to our application we need to create a special folder and that is called www root and when I created you can see that it shows a special icon this means that this anything that is under this folder will be publicly exposed to the whole world yeah because those are static files like images scripts so those files need to be accessible to any pages in the application and also accessible to the outside world here I want to create a sub folder and I'm going to call it lab so it stands for library and then another subfolder and I'm going to call it bu strap after that we paste everything that I downloaded into the bootstrap folder and you can see the CSS files and there's JavaScript files that came with bootstrap and of course they're showing up over here so now since this folder is exposed outside if we run our application we should be able to just access any of these files through the browser so let's try to give it a try Okay so if we go to lab SLB strap SL CSS and then inside CSS we have this bootstrap.css so let's go to bootstrap.css however it says that the location cannot be found so what has gone wrong actually in our application the access to the static files are not enabled yet in order to enable that we need to add the static file middleware so we can say say app.use static files so with this middleware added ASP core will be able to go into the WW root folder to locate the static file that is requested so with this middleware added let's get a try again again let's go to lab SL bootstrap SL CSS SL bootstrap.css and now you can see the bootstrap.css file is loaded on the page with the CSS file added let's reference the CSS file in our layout file so let's go to Shared layout and then inside head we can use a link element here reference to stylesheet and then here we can point to lab bootstrap CSS and bootstrap.css now we can work on making the application look slightly more beautiful I'm going to add a container class over here which is a bootstrap container and let's run the application again and see whether it makes any differences or not now you can see it looks completely different uh right now I have 150% so let's zoom out and this is 100% so you can see that homepage looks different categories page also looks different inside here everything looks different and slightly more beautiful it has a margin on the left and margin on the right and I'm going to copy and paste a header that I prepared so that we can have a menu bar on the top okay I pasted this header over here and this comes from bootstrap as well there's examples you can copy them and just use them I created this empty menu bar and if we want to add some items here we can add them like this first We'll add a list item and then this is going to have a nav item as a class and then inside here we can just add a anchor link we're going to use these two classes as the class and we are going to navigate to let's say the homepage and index action method and here we're just going to say home and we going add another one which goes to our categories page so I'm going to say categories and do you still remember what is the URL that goes to the categories page that is categories and index so with this change made hopefully we can see the beautiful Manu bar okay the Manu bar is showing on the top we click on the home it goes to the same page we click on categories it go to the categories page with the beverage link and meet link here click on the category it goes to the category number one going back click click on meet go to category number two so in this video we use the static file middleware to support the use of static files and we have used bootstrap navigation bars to implement in the menu bar that's all I want to cover in this video and I'll see you in the next one another thing I want to cover that is related to layout is the concept of sections right now our layout file works like this so imagine this is the layout file we have a render body over here and like I mentioned before this is like a placeholder where the views will be rendered to replace this placeholder so this first view will be rendered over here the second view will be rendered over here as well and so on and so forth but as you noticed this is just one section in the entire body of the layout file what if we want to have another placeholder right another section so for example on the top I have another div and I want to specify a placeholder here so that some part of the view in each one of these View files will come into this particular placeholder a good example is a header I can define a header region in the layout file and each view may have different header contents when they're linked together the first views Hider contents will go into this placeholder and the second views header content will also go to this placeholder when we try render the second View and of course the rest of the content will go to the body placeholder over here fortunately ESP core MVC provides this type of functionality and that is called sections let's jump into video studio and go ahead and Implement that so here in the layout file if I use a div to surround the render body method then I can add another div and inside the St I'm going to put a section so to do that instead of render body I'm going to say render section and this function takes a parameter that is the name of the section so I'm going to create a title section and then for this div I also want to apply a padding let's say padding at the bottom size is number three so that there is a gap between the title and the body so then let's go into each one of the views that we want to use the title section and let's go to homepage so we want to render this into section of course we don't need the line break anymore because we added the padding so here we just want to say add sign section and then we just need to specify the name of the section after that I just want to put a pair of Cur braces and then move content that that I need to render in the section inside the curly press and with this change the welcome to home message will be replacing the section placeholder and the rest of the HTML will be replacing the body placeholder so the same thing needs to be done in other Pages here I want to say categories and it's going to be H3 instead of H1 so let's keep this one without using the section and let's run the application see what happens you can see immediately it throws an error it says that the layout page cannot find the section title in the content page edit. CSH HTML so when we specify the section like this it means that this section is a required section all of the views will have to use the title section so let's go to edit and put our section over here and let's move this HTML inside so with this change we should be able to run the application and now you can see everything works like before we can't tell any differences but we are actually using the section so how do we specify section that is optional this render section method has another signature which specifies the second parameter to tell whether the section is required or not so if we don't want all the pages to use this section then we can specify false by default the required parameter is set to True let's keep it as default so that we can use title section on all of the views this seems to be not very useful but if you have something that you want to place above or below or as the background of the section then you can just specify in the layout view you don't have to specify that in every single view for example if I just want to add a HR element then all of a sudden all of the pages will have this HR element displayed okay that's everything I want to cover in this video and I'll will see you in the next one in this video let's talk about a static in memory repository eventually in our course we're going to use clean architecture in which we are going to have a use case layer that encapsulate all of the business logic then we're going to use dependency injection to inject the use cases into the controller the controller will then use the use cases to populate the data and then does the rest of the things that we talked about before when we use use cases the data will be injected into the use cases and that's a fairly complicated but very very useful architecture that we're going to learn in later part of our course for now we want to learn the MVC framework therefore in this lesson I want to introduce a static inmemory repository where all of the data operations are encapsulated so the data operations have create read update and delete all those crot operations will be encapsulated in the static repository and then the controller will use the static repository to retrieve data and populate the model with this very simple repository we can focus our ATT attention on understanding the essence of the MVC web application framework in this section since we're working on categories so I have prepared the inmemory repository for categories and let's take a look what I did is I added the categories repository inside the models folder so this is just a simple class let's click into it and we can see that this is a static class and it has a static list of categories because this is a inmemory representation of the data right it's inmemory data store so therefore we're using a list to host all of the data so these are the categories that I seated the IM memory data store every time you run the application you will have at least three categories to work with and then the rest are the operations as I mentioned we have four different types of operations we have create we have read we have update and we have delete this add method is the create when a new category is passed in first of all we need to get new ID this one comes in it doesn't have a ID so we need to figure out what is the maximum ID and then we plus one and we assign that to the category ID of this object and then we add this category object into our categories list so this is how my IM memory create operation is implemented and then of course this is very straightforward when we get all of the categories we just return categories list next one is we want to read category by ID so the category ID is passed in as a parameter we use Link to get the category that has the same ID if it's not n we want to create a copy and then we return the copy so this mimics a actual database in a database the data is stored in the file that instance of data is never returned back to collar the collar always gets a copy in other words the collar can never touch the actual data without running any statement so that's why we're creating a copy otherwise we just return this category the caller whoever calls the the function will be able to just update the properties of the category and that affects our IM memory data here right that's why I'm creating a copy of the category and of course if the category is n then I just return now so therefore I have a question mark here to say this is nullable now comes to the update we have two parameters first of all we need to verify that the category ID that is passed in is the same as the categories category ID and then I get the category to update if it's not null then I update each one of those properties here I don't have a lot of properties if I do then I can use automapper to map the properties to properties which is very simple to use you can do your own research and use that in your own code if you're interested last but not least we have this delete category and it's very simple we use Link to get the category if it's not now then we just remove from the list so this is my static repository for categories and in the rest of this section we're going to use this static inmemory repository as the data store and that's everything I want to cover in this video I will see you in the next one in this video let's try to understand what you need to do when you want to implement a web page with the MVC framework because the MVC framework has a lot of moving Parts the approach that I suggest you to work with is what I call the controller model and view triangle first of all we want want to handle the request with controller's action method and then we use our underlining architecture to populate the model in this case we want to use reposer that we just created and then we combine the model to The View and then we work on The View right and the rest will be taken care of by MVC framework in other words The View will automatically be returned by the controller in the response to the BR to be rendered so first let's take care of of the controller then let's combine the model to The View and then let's work on the view let's take a look at what we need to implement in this video in our categories controller here index action method currently is doing nothing it basically just Returns the index View and then if we go to our index View for the categories currently we just have two hardcoded categories so let's use the category poster that we created in the last video to actually return some real data let's follow the approach of the controller model and view triangle therefore first we come to the controller because controller has already been implemented so there's nothing else to do then we jump right into the Second Step which is to load data and then populate the model here in order to load the data uh we can just say categories right and how do we load the data can use our categories rep poory right here and then we can just call get categories and this one returns all of the categories in the IM memory data store and now we combine the data to The View and you have seen this over here we can just put the model right here in the view at this moment we have taken care of the controller and we have loaded the model with data and of course we have combined the model to the view now comes to the last step which is we need to work on The View because the action method is Index this view corresponds this view because the name is the same so let's go to this view so in this view first of all we want to specify what type of data we're working with when you look at the controller this categories is a list of category so therefore we are working with a list of category so this is the type of the model that the view is working with here we need to import the namespace now we have the the type of data then we can use Razer Sy to help us to render HTML so let's delete this here when you want to use any c expressions or statement or Cod blocks we want to start with the at sign and of course here we want to Loop through the list that is combined with this view so we can use for each or we can use four I prefer to use for each here and just like writing a reg C you just use for each normally and here I'm going to say for each category in our model so this model represents the instance of this type of data right and of course this one corresponds to this particular object so now I just simply want to display the name of the category so I use Li element and then over here because I have used HTML the low of C has been broken here I cannot just access the category if I do this this is not considered as C expression anymore I have to use the add sign right why do I have to do that as I mentioned because I used HTML already so the flow of C is broken so I have to use S sign here I just want to show the name of the category for now all right let's run our application and see whether this work works or not we're looking at our homepage and let's go to categories now you can see beverage Bakery and meat those are the seated data in our IM memory static repository that means our code is working we are finally displaying some real data and again in this lesson the takeaway is how you work with MVC first you handle the request so you come to the controller and you deal with the controller and then you use the underlining architecture components in this case we're using repository it's a static memory repository to load data into the model after that you want to focus The View so you come to the view specify the type of the data that you want to bind to the view or combine to The View and then you work with reader syntax to manipulate HTML that's everything I want to cover in this video now I'll see you in the next one in this video let's talk about using tag hbers to help generate link the scenario is this this is the categories page where we list all of the categories for now we're using an ordered list but let's replace this with HTML tables after that we will generate links within the HTML table so I'm going to delete this and before I add the table I want to be more protective I want to make sure the model that is sent to this View is not n and also I want to make sure that the count is greater than zero because I know that this model that is combined to this view is a list so therefore I can use comp so only in this case do we display the HTML table that contains a list of categories so I think this is called Defensive programming just to make sure that we don't create any exception so I happen to have the HTML I think everybody knows HTML so I'm not going to teach HTML in this course so therefore I'm just going to copy and paste what I have and then I'll explain okay I have some bootstrap classes apply to the table and in table I have three columns name and description and this column is empty because in the TD that corresponds to the header I want to add a edit button and only when the user click on the edit button button do I want to redirect the user to the category page so I can use a anchor element as well but then I'm going to apply a button class so that it will look like a link button like this and then the caption is edit so here's the question what the URL supposed to be here if we write the URL directly it would be categories so this is the controller and then edit that's the action and then the ID here so for that one way to do this is to use explicit razor expression we're going to use a s sign with brackets so when we have brackets like this this is called explicit razor expression and then here I can just add any c expressions and the C Expressions will be evaluated right for example I can use Plus or I can use string interpolation and then here I can add the ID which is going to be category do category ID add sign with brackets and everything in here is just regular C expression with this change I can try to run the application okay so I have this table it looks much better than before and then I have the edit button and if I however my mouse over if you look at the bottom left corner the URL is actually properly rendered so if I click on edit I come to category number one if I come to meet then I see category number three so everything looks okay but there's a better way to generate links and that is called tag helpers so I'm going to delete this href and you can see that we have HTML element and we have this attribute a tag helper most of the time it refers to attribute name to use Tag helpers we need to add the tag helpers first so we can scroll up at the very top we can say add tag helper I'm going to add all of the tag helpers and after we specify this then we can come over here and if we just start typing you can already see actually from the intellisense that we have all of this attribute start with ASP so these are all tag helpers so in order to generate a URL that can be processed by a controller's action method we can use ASP controller so this specifies the controller that the link should use next one is going to be the action so we are going to go to the addit action the next one we need to provide the parameter so I'm going to say ASP root and then you can see this one has a dash so this one refers to the parameter that the edit action uses so let's go to controllers here you can see that it's called ID so therefore here I'm just going to add ID and what goes here is the category do category ID so this at sign without brackets it's called implicit reader expression the one that we used with as sign followed by bracket that's called explicit rer expression so now we have these three Tech helpers combined together to help us generate the same URL L that we used the Razer syntax to generate you can definitely use the explicit Razer expression to generate the URL you can also use Tech helpers to Target certain controller and certain action method in the controller and provide the parameters by using tag helpers you have different options and it's up to you what you want to do I personally prefer using tack hubbers I think it's cleaner and with this change we should be able to generate the same URL like before so let's go to categories and we can see everything is correctly generated category number one category number two and also category number three now that we know how to use TCH helpers another thing I want to do is to replace the URLs that we put in the layout file so in the layout file which is in the shared folders let's go to the layout file here we're just uh hardcoding the uh the string right that's perfectly valid but I also want to use Tech helpers here and do you remember how to do this so ASP Dash and the moment I start typing I realized that I did not add Tech helpers right so I have to do that on this page as well it looks like we have to add the tech helpers on every single page where we want want to use it but that's not necessarily true in the next video we can resolve that issue briefly but here once we add this we can use all of the tag hoers so I'm going to say as- controller so we're targeting the home controller so we say home and then we're targeting the action which is index same thing over here we're targeting controller which is categories and the action is is index now let's just test it make sure it still works correctly okay let's click on homeage still goes to homepage click on categories still goes to categories and that's everything I want to show in this video I will see you in the next one in the previous video we have encountered a problem so let's go to the layout file you can see that when we try to use Tech helpers in the layout file we have to add the tech helpers like this and also when when we are trying to use Tech helpers in the categories view here you also have to add Tech helpers like this in fact we have been experiencing this problems in the past lessons so look at this when we are trying to use the category class we have to import a namespace like this and we did this in the index file we did this in the addit file and in the future when we work on different other classes we will encounter the same problem so is there a place where we can centralize these using statement as well as at Tech helpers this type of statements yes there's a special view we can add to enter the views folder and that is called and thecore view import so let's go ahead and add view so add just add a regular Reserve view that is empty and then we will have to name it as ncore view import and then we can put our using statement at Tech helpers all of those type of statements in here to centralize them so let's go into edit we can remove this go to index we can copy and cut this go to home home is fine go to layout file we can delete the at TCH helpers and let's go to the view import file and just paste it over here so how does it work this works a little bit similar to The ncore View start however ncore view start is used at runtime right everything that is within the view start file is executed before the actual View files are executed here in ncore view import file these statements are used at compile time so once I pasted it over here if we go back to edit you can see that the category becomes color coded here categor is color coded and the text Tech helpers color coded as well in the layout file the tech helpers are also highlighted so you can see the purpose of this view import file which help us to centralize all of the using statements and add TCH hoverers right we don't have to add them each and every single view that's everything I want to cover in this video and I will see you in the next one in this video let's talk about model binding when we were talking about MVC one of the steps is that you know after the model is populated with data the model is then combined with the view so this is One Direction from model into the view there is another Direction where the data comes from the browser right either the user inputs a URL that contains the data or the user inputs some data in the page as as part of the form and then send through the request to the control contrer in the controller action method we have to have a way to receive those data and that is called Model binding we have talked about this briefly in one of the previous videos but we didn't give it a name in this video let's talk more about it let's take example in the categories view we use TCH helpers to generate the URL and this is the data that we want to pass from the browser to the controller's action method and in the controller's action meod here we have this ID which corresponds to the root parameter name here ID and therefore that data is received as the parameter this in as core is called Model binding and this edit action method is a HTTP get action method if we don't specify what the action method is it corresponds to the HTTP get action method although everything everything I cover in this video also applies to other type for example HTTP post action method and for model binding the data can come from different sources in sp. qu we can actually specify where the data come from so in this case the data comes from the root so we can say from root and then if we run the application we are going to have it's going to work the same way as before so go to categories click on addit Curry so we can see it goes to category number two after we specify this comes from the root we can no longer pass the data from the query string anymore so remember in the previous one of the previous videos I said that we can do something like this now you can see that it shows category zero no matter what number you put here it's always going to be zero because it has be done a coure failed to do model binding so in this case if we want to specifically specify where the data comes from right we can actually specify the data come from query and if we recompile and run the application then you can see that category 133 because we specified category 133 we change to 135 then we can see 135 but in this case if we want to use root then we wouldn't be able to use 135 now this becomes zero if we look at Microsoft documentation here you can see that model bindings data can come from these five different places if we don't specify where the data come from just like what we did before removing this attribute then SP spon cor is going to go through all of these five different places to locate the data if it fails located data of course going to do whatever it going to do whether it's a reported error or it's going to provide a default value for the parameter is going to do what it needs to do another thing I want to talk about is that for model binding right now the data is just a simple value it bonds to a simple type data binding can actually bind data to complex type so for example if I specify category and then the parameter becomes category so let me comment out this line so if I put a breakpoint here and run the application and then go to categories of course this link is not going to work anymore you can see it didn't receive any data but if we use qu stream to specify category ID is one and presign uh name it beverage and hit enter now if we check you can see it actually received data right why it received data it it's just because the question names corresponds to these properties in the class of course we're not going to do this I'm just showing you different possibilities let's roll back to what we did before okay so regarding model binding we are going to cover a little bit more in the future when we work with forms at this moment since we are here we want to actually load categories from the data store right because right now we just passing the ID to the category we're not actually loading the category from the data store so let's do that we want to use the categories repository and we want to get category by ID here we just need to pass in the ID and of course this method here returns null if the ID doesn't exist in the data store but I think that is okay so we're going to just create the the category variable like this and then here I'm just going to say if it has value then I use the value otherwise I'm just going to use zero so another thing we want to do is let's go to the view right click on the action method you can click on go to view it takes you to the view and now that we have actual data we don't want to actually display the category ID let's at least display the category name and here we want to be defensive right if the model is not now then that's when we want to render the HTML okay let's run the application and give it a test let's go to categories and let's go to beverage and we can see the name of the category go to Baker we can see the name go to meet we can see the name let's do a edge case testing so let's let's say that I put in number 30 now I don't see anything that is the correct Behavior because number 30 doesn't exist then category returns null here in the view if it's null it's not actually going to render anything of course you can provide a error message here I'm not going to do that in this lesson in this video we have talked up a little bit about model binding and then we retrieve the data from the inmemory data store that's everything I want to cover in this video I'll see you in the next one in this video let's try to use Hur to help us to create a HTML form we're looking at the edit category page on this page we not only need to display the category information but also need to be able to edit the category information and for that we will need a HTML form the form tag specifies the method because we want to make a change therefore we're going to use the post method and for a normal form tag it has a action attribute so this is the place where we need to provide a URL and this URL is something like this so categories edit what this means is that when the form is submitted it will go to this particular URL to handle the submit form action however in Theon core there's easier way to do this because it is always the action method who handles the request therefore it's more intuitive to specify the controller and its actions separately as opposed to hardcode a URL here in the action attribute this is where we use Tech helper we have used Tech helper to create navigation links here we can still use techer to specify which controller it goes to in this case it's categories and then which action it will go to in this case is added now here we need to create the name field the description field we also need to display a submit button so let's go ahead and do that we're going to use bootstrap five we're going to use a row class along with a bottom margin and within here we can specify to and for now I'm going to have two columns one is column so this number two is the size the margin bottom number three is also the size so in column two we're going to use a label and this is where we show the label for the name field and of course we can just hardcode name here to specifying the label for the name field but we can also use a tack helper as qu tag helper where we can say for which field under the model specified here this label is four here you can see that there there's intellisense and we can select the name field here as done core will look look at the name field and we'll be able to generate the string for us when it renders the HTML and we can provide a class so we're going to say column form label by the way how to use bootstrap classes out of scope of this course so you can check out the documentation of bootstrap next we're going to add the the field column and for this one it's going to be slightly bigger so we're going to use size number six you can play with is the size and determine what size is good for you here we're going to use a input field and the type is obviously text and again this field is for name and we're going to have form control for the class name so we completed the name field we can actually give it a try and see how it looks like right now so let's go to categories and let's add click on the edit button you can see the first field is displayed and let's press on F12 and check out the name field here you can see with the TAC helper it points to the name field it generated ID which name and name of the field is also name so because we have the ID and the name here is when the field is submitted to the controller action method the model binding process that we talked before is going to be able to recognize to which property in the class this field needs to be bond to so let's go back and continue to implement the next field which is the description field and for that we can just copy and paste the name field so here we only just need to change the field of the name in this case is description for the label and it's also description for input field now last but not least we're going to have a submit button in here we can also copy this row here and paste it now we want the button to be in the First Column and the second column we can leave it as empty so here we're going to have another input but this time it's going to be a submit button instead of a actual field for user to input information and it's going to be a button and it's going to be a primary button the value is the caption of the button and that's going to be save because this is added page okay let's run the application and check out the page again let's go to category and click on the second one which is pickory and we can see the name in description is properly rendered we can try the last one and it's also properly rendered okay in this lesson we have learned to use Tag Hubers to help us to create HTML form and with the TCH helper it can specify which controller and action method will handle the post request from the form and also we learn how to use asp4 Tech helper to help us to specify the field name label and the field itself that's everything I want to cover in this video and I'll see you in the next one in the previous video we have implemented the edit form and when the user click on the submit button we're supposed to handle the HTP post request so in this video let's do that as you know already when the form is submitted it's going to go to the categories controller and go to the addit action so let's go to the controller currently you can see that we already have a addit action under the categories controller will this edit action method actually handle that request no we need to have all of the fields posted back over here so the added action that we specified in the edit form here will have to be able to see the value of the name field and the value of the description field so then what do we do when we already have a added action method we can create another edit method with the same name but different signature here we want to receive an instance of the category class and we also need to specify with attribute that this particular action method handles a HTTP post request you don't specify anything on the action method the action method handles the HTTP get request that's by default so we can delete this but but here because the HTML form uses the post method we need another addit method and those a post request here and when the form is submitted model binding will kick in and all of the fills in the form will be mapped to the properties instance of the category class here let's take a look at the category posture here here we have a update category method we can use this method to help us to handle the request so we're going to say categories repository and then we're going to call the update category method here it receives two parameters the first one is the ID of the category so we're going to provide ID of the category which is category. ID and here the second one is just the category object direct the user to the categories index page so this action this action will go to the index view which is going to display a list of categories so for that we can use a helper method which is redirect to action and here we can specify the action name without specifying the controller's name which means that we are using the same controller we can say name of index so this will redirect to the same controller which is the categories controller here and index action method which is this one so this is going to help us to display a list of categories and that's what we want to do okay let's set up point and then run the application with debug okay now we're looking at the homepage let's go to categories let's add it the first one and let's try to click on the save button which submit the form hopefully it's going to trigger our HTTP post edit method okay so our break point is hits that means our edit action method is created correctly so far now we have the category correctly mod Bond here well there's only one problem the category ID is zero so when the category ID is zero it won't be able to update the category because we need to use the category ID to locate the method but if we run through this we run into it it will not throw any exception because the category to update is null and then it will just redirect to the index view which is the list of category right here so in the next video we will have to fix this problem where we don't see any ID of the category just to sum up what we learn in this video so in this video we learned to use HTTP post attribute to decorate a action method for handling form submissions and here we use the model binding to receive data that is submitted through the edit form over here and because the TX helpers that we we used from the previous video espon core knows which field corresponds to which property in the category class so therefore this category object will be able to receive all of the information in the form so that's everything I want to cover in this video I will see you in the next one in the previous video we were able to submit the form to the action method that handles the HP post request but we encountered one problem where the category ID here is not actually submitted and remains zero so in this video let's resolve that problem and to resolve it we have to think about why the category ID is zero let's go to the addit view here and we can see that we have a input for the name we have a input for the description and for both of the fs we do see data in the edit action method but we don't have a fi here that stores the category ID and that's why when the user clicks on the submit button the ID is not submitted back to the controller action method and therefore the controller action method cannot receive that ID so in order to solve that problem we can add a field in the form that keeps category ID but you may say that if we do that the user will see the ID on the form and that's not actually what we want at least it doesn't look good but we can use a hidden field a hidden field will still be submitted when the user click on the submit button but it will be hidden to the view of the user so we can just put it on the top or on the bottom or anywhere it's hidden anyways so here we can specify the type of the field is hidden and again here we need to specify the value of the ID and you can think about what tag helper we can for this it is the ASP 4 Tech Helper and here just use category ID and that is it now we can set a breakpoint here and run the application again now let's go to category and select the first one again and let's change the category description to beverage category for example and click on Save but now let's hover the mouse over this object here and now you can see the category ID is properly submitted and we can see the change of description now let's just run the application now it comes back to the categories page here or categories view here and we don't see this description change I found that we have a problem in the update category method in the repository where we use the Gat category by ID method that returns a copy of the category and then we update it but because this is a different instance from the instance that we stored over here so therefore it won't actually update the category in the memory so instead of using the get category by ID method let's actually use this link query here to help us to actually get the category in the map data store so let's change it to this one and then let's run the application so this time I'm not going to run debug hopefully it will just run without any problem so let's go to categories and let's this time change the second one and we're going to say Bakery category click on the save button and now we are redirected to the category list and we can see that description is changed let's click on edit button again and you can see that everything is running correctly and that's what I want to cover in this video I will see you in the next one in this video let's work on form validations with data annotations let's go to categories controllers and let's make sure that this breakpoint is here and let's run the application with debug now let's go to categories and let's choose any one of them now if I delete the name of the category which shouldn't be allowed you cannot have a category doesn't have a name you may have a category that doesn't have a description so if we click on save button now if we H the mouse over this object here you can see that the name is now if we proceed with this continue button here you can see that the name of the beverage category is gone so that's why we will need some sort of validation on this edit category page that validation should be triggered when the save button is clicked on and it should prevent the user from from saving the category if the information on this form is not valid we should always validate users input because users may make all kinds of problems due to different reasons one way to do form validations is to use data annotations and to do that let's stop debugging first and let's go to the categories class definition and we can see we have different properties here in our case we want to decorate the name property like I mentioned you cannot have a category without a name so I can decorate with a c attribute and that is called required and I can do a control dot to import namespace which is Ender component model. data annotations now with this attribute added to the property we can run our application again and see what kind of difference this makes let's go to category here notice that the the name comes back that's because we are using the inmemory data store every time you run the application default categories will show up right all of the changes you made in the previous run will be gone so let's click on let's say the same category here and now let's delete the name again and click on the save button of course we're going to see the same problem the name is still now but we go to the watch window here and let's type in model state so this is a object that is defined within the controller class if we look at the value of is valid and it says false validation status invalid so what this means is that although the controller is still handling the request the controller actually knows that the form values are not valid and it's up to the developer to handle that invalid request over here so what we need to do first of all of course we need to stop debugging secondly we will need to check the model State here so we can use is valid here only when the model state is valid do we actually go ahead and update category and then do the redirection now what should we do if the model state is invalid where do we want the user to go of course we need user to see the same category page and on that category page we need to see error message so that the user has the opportunity to correct his or her mistake so therefore just like any action method if we want to show The View we just return the view just like this and we feed the category into the view combine them together generate the HTML and because we have the category here so user can see the data that he or she entered and then has the opportunity to correct the mistake and now when we run the application and go to categories or beverage and try to delete the name again you can see that we redirected back to the category page we don't see the name but we don't see the error message also however if we manually go to the categories page you can see that the change is not actually made so the only miss step here is to display proper error message and let's go ahead and do that let's jump back to Vis Studio this time we need to go to the view so right click on ADD method and click on go to view here the view is the place where we can make changes to display the error message and guess what we use Tag helpers to help us to display error message so we can have a Dev on the top and we can use TX danger to display the error message in red and we we are going to use ASP Das validation Das summary here and here we want to use all because we want to display all type of error messages the other one that is available is model only so this shows only the error messages comes from the model I suggest that we always use all so that we display all type of error messages now we have the summary for displaying the error message we also want a specific error message beside field name here so for that we can add another div right here and this time we can use the column class so this one is going to choose a size automatically because we are not specifying the size number so here we're going to use span and then we can still use the same class here which is text danger and here we can use application validation 4 and for which field of course in this case it's for the name field and then let's close the span element properly and let's run the application again now let's go to categories and this time let's go to meet and let's delete the name of the meat and now we can see the eror message summary on the top and error message for the specific field so if we have more than one field all of the error message will be displayed on the top this in the summary area and then individual error messages will be displayed just beside the field so in this video we covered form validation with data annotations to do that let's summarize first step we need to use data annotations to decorate the properties and there's different attributes you can use some of them you can use to limit the range for example if you have a number number let's say age you want the age to be greater than zero so you want to put a validation attribute for that you can go to Microsoft documentation to find all of the available attributes for data annotation type of validation and use them accordingly that's the first step right use the attribute to decorate properties of the model class secondly we go to controllers and check the model State the third step is that we need to go to view and put a validation summary if you want to see the summary on the top or on the bottom or on both places and then you can display individual error messages right beside each field if you want the user to see them so that's everything I want to cover in this video I will see you in the next one this video is a assignment video in this assignment you need to complete the add category functionality so here are some requirements and some hints so on the categories page you will need to add a add button over here and when the user clicks on the add button you will need to redirect the user to add category page was the name and description empty and when the user clicks on the submit button of course you will add the category to the inmemory data store for example if I say category number one the description is category number one as well and then I click on the submit button it will create the category in the inmemory data store and then redirect the user back to the categories page where you see a list of categories and you must see your newly added category show up in the list another thing that you need to pay attention is that while the user tries to click on the submit button to submit the category you will need to do your validation right so for example if I don't enter anything and click on the submit button I have to have this name field validation show up right here okay so all of these are the requirement and here are some tips when working on MVC applications these are the steps that I suggest you to follow these are also the steps I personally follow when I work on MVC applications so with m v and c I suggest you to change that order to m c and V so first you will create your your model and then you work on your controller right the controller handles request right once you finish your controller you go ahead and Implement your view sometimes you need to jump back and force between the controller and view but most of the time you can complete your controller and then you work on your view of course in this case we have already created a model which is the category model you just need to focus on creating the controller and then the view okay that's everything I want to cover in this video and you can start with your assignment and hopefully this assignment helps you exercise most of the concept that you have learned so far in this course I'll see you in the next video in this video let's work on the assignment like I mentioned in the previous video I suggest you to work with this sequence the model the controller and the view and since we are working with categories and the model has already been created so let's first focus on creating the controller well we already have the controller class so when I say controller what I really mean is the action method or action methods so first of all just like when we implementing the edit page we need a pair of controller action methods a action method that handles the HTTP Gat which is this one and then another one that handles the http post so therefore let's add these two action method and let's start with the HTTP G for H TTP Gat we do not need to specify the attribute so by default an action method without the attribute is the one that handles HTT get so here we can just call it add and then we don't need any parameters because we don't need to handle any information here the form will be empty here we just need to return to the view and we don't need to specify the name of the view because we are going to create a view with the same name as the action method of course you can specify the name of the view if you want so here we implemented the controller action method already next step is that we need to implement the view the first view we will need to work on is the index view where we will need to add a add button and that that add button will use this action method that we just added so let's go ahead and Implement that let's scroll all the way down to the bottom and then let's add a line break here and after that we can add a button so are we going to use this button Element no this is going to be a link so we can use a anchor element and with the anchor element we can specify that this link actually looks like a button how do we do that we use a bootstrap class so button and button primary next thing we're going to specify where this link will go to and as we have learned before we're going to use the tag helpers ASP controller we specify where which controller is going to handle this so of course going to be the categories controller and then we're going to specify the action and this is going to be the app add action and now we can specify the caption and the next view we're going to work on is the actual ad view to do that we can right click on the action method and then let's click on count add view now select Reser view empty now we just need to make sure the name of the view corresponds to the name of the action method okay let's click on Save and this view is going to be really really similar to the edit view therefore we can just copy and paste this whole thing to the ad view here of course we will need to change title section to show just add add category there's going to be no name to be displayed now inside the form we do not have the category ID right because we're dealing with a new category so therefore we don't have the category ID we don't need to worry about it and we have have two FS a name and a description and now we have the submit button the type is submit but the value we will need to change it to add so this is the caption of the button and when this button is clicked on the form will have to be posted back to the controller so who's going to handle that we have to change this action to add now I mentioned in the previous video we will need to take care of the validations but because we have just copy and pasted so we have the summary and we have individual validation error messages beside each field so we don't need to worry about anything else now the next thing is to implement the next action method that's why I said that sometimes you need to jump back and forth between the view and the controller but I suggest you to start with the controller so now now let's go to the controller contrer and we will need to implement the next one which is the the action method that handles the AG TTP post and visual studio knows what I tries to do so it actually generated the code for me so I don't have to specify where this comes from but if I want I can specify that this comes from the form right I don't have to do because ASP core will Loop through all of the possible sources and be able to do the model binding correctly I will remove this now inside the action method for anything that handles HTTP post first thing first without thinking about anything else we need to make sure that data comes from the model binding is valid so therefore we're going to say if model state is valid then we can do something what are we going to do we are going to use the categories repository to add category and then we can just simply feed the parameter category to the rep repository and when everything is successful we're going to redirect to action not the add action we can redirect back to the indexed action it's up to you if you want to redirect back to the add action along the user to continuously add categories that's fine but in this case like I mentioned in the previous video the requirement is that you redirect the user back to the list of categories right to that page now guess what should you do if the model state is invalid just like what suggested by Visual Studio you will need to return back to the same view here because we are not specifying which view we are going to go go to it's going to go The View with the same name as the action method and we are feeding this parameter to the view so therefore if you input something wrong that wrong data will still be there allowing the user to correct the mistake so let's review to see whether we have done everything correctly we have two action methods added and we have ADD view added over here we implement the title section and here actually we don't need to verify whether the model is null or not now because we're not relying on the model anymore and seeing this maybe we can go back and add some defensive coding in the addit view here sorry about jumping to this point we have tested that the model shouldn't be null for this but we haven't tested the model shouldn't be enough for the form so let's just be this defensive and add this as well so run the whole form with it so this is going to make sure it's act safe okay let's come back to the ad View and continue so we don't have to surround this with whether the model is going to be null or not because we don't have a model yet okay I think we have implemented this correctly and let's give it a try if it's not correct we can just go ahead and correct the mistakes when we are coding real word project it's impossible to always get everything right it's the first try so being a good programmer or being a good software developer means that we have to have one of the most important skill which is to be able to debug efficiently okay this is the homepage let's go to categories and we can see our we at but button over here let's click on the ad but and it takes us to the ad category page that's very good and let's click on the add button to make sure the validation is triggered okay the validation is triggered the problem is that we see that the description field is also required but if we go to the categories model here we can see that we did not actually specify that description is required that's because by default as Cor appli enables nullable click on the project and then we can see the project file we can see that nullable is enabled by default that's a good thing we don't have to disable it but in order to actually make this description not required right optional uh we can use a question mark over here and when we do that let's go back to the application again let's click on the add button again and let's click on this add button now you can see that the only thing that is required is the name field okay so validation also works and let's add this so I'm going to use category one as well and here I'm also going to use category one well maybe add something else description and now let's click on the add button to see whether the post method works okay so category number one is added over here and we can also see whether we can addit it okay so can add this or maybe we can just delete the whole thing and click on save button now our category one is Chang it as well so everything works as expected I hope you have also completed your category ad functionality successfully and if you have any questions please let me know otherwise I will see you in the next video in this video let's learn about using JavaScript in been on MVC application so the scenario is that we want to delete this category one in our categories list which we added in the previous video we need to add a delete button over here and when the user clicks on the delete button this category will be deleted but before it's deleted we need to warn the user ask him or her to confirm whether he or she really wants to delete the category so that's where we need to use JavaScript and let's think in the model controller and view MCV order we already have the model so next is the controller what type of controller is that it's going to be a HTTP get controller so when the delete button let's imagine there's a delete link over here right when the user clicks on that delete link we are going to redirect that user to a place where the delete action method will be called so let's go ahead and Implement that delete action method let's go to the controller and then let's add a action method here and let's call it delete here we need to know which category to delete therefore we're going to passing the category ID and once we have the category ID we can then use the categories reposter to delete it so passing the category ID like this and then we are just going to redirect to the index page and from the next page we can verify that the category is deleted or not we have implemented the controller action method this next step we're going to work on The View so in the view of the index page we are going to add another column so in the header is going to be just a empty header and over here we're going to add another TD and here it's going to be a link so we're going to use the anchor tag and let's just going to be the same bootstrap class as as the addit uh link now we are going to take the user to the delete action method so therefore we specify the controller first which is the categories controller now the action which is the delete action we just implemented now we need to pass in the ID and just just like the uh the added button and we're going to specify ASP rot and specify category ID like this so say category. category ID and here the caption is going to be just delete so with this change when the user clicks on this delete button uh ASB qu is going to use the categories controller the delete action fitting the category ID right so it's exactly this one and then it's going to go ahead and delete the category the problem is that we want to ask ask the user to confirm whether the delete is intentionally or a mistake so for that we need to run a JavaScript and the easiest way to do that is that we trigger a confirm a pure JavaScript confirm dialog but this is a view right how do we add JavaScript over here remember everything inside here will be rendered in the render body placeholder so let's go to the layout file to control comma layout and double click on here now we have the render placeholder render body placeholder right over here so if we put any JavaScript in this file is going to be just inside the sff and that's not really what we want the best practice to render Javascript file is to render that just right before the body Clos es right before this tag so it doesn't affect the performance of rendering the actual content for that we can use a section like this remember a section is a place where we specify in the layout file and then in any of the views that uses this layout file we can specify the content that will eventually go into this section replace this section in the layout file so therefore we can add another section and we can use the aink way to render section you can see we have render section and render section async I want to use the async version here because we may have a lot of script to render so I use async version to improve the performance here the first parameter is the name of the section which is later will be used in individual views to refer to the section so I'm going to say this is a script section and then I need to make sure I mark this one as not required only the ones that actually use actually need to run their JavaScript will use the section other views that don't need JavaScript don't have to use this section so therefore I say required is false so now I have the section defined in the layout file I will then go ahead and go to the index field where I need to use the section to Rend there some JavaScript do you remember how to use a section use add sign and then we we say section and then we specify the name of the section which is script then we use curly Braes So within here we can write uh HTML and here we use the script tag and inside the script tag we Define the JavaScript functions so I'm going to define a confirmed delete function and inside here I can simply just call the confirm JavaScript function and I'm going just ask are you sure you want to eat this category and after that I will have to use this confirm delete JavaScript function inside this anchor tag tag so here I'm going to say unclick cck and then I'm going to say return confirm delete and that's it before we run the application let's review the code here I can see that I have a typo here so instead of confirm it should be confirm and then let's go ahead and run the application test out all right so we're looking at our categories page and we have lost our category one because we have rerun the application but we can delete this any of the category before we do that let's go to developer console and let's see we have the script section over here that rendered so we have this confirm delete right and then if we check this delete button we can see that we have this onclick render over here so this function will be triggered this particular one so let's click on let's say the second one Bakery then we can see our confirmation dialogue over here if we click on and so nothing is going to happen if we click on yes are you sure you want to delete this category we click on okay then you can see that the category is deleted so we can try again delete the bakery okay Bakery is deleted last one we say cancel then it just comes back nothing is happening to summarize what we have learned in this video we have actually gone through the whole process of model controller View and we created a delete action we triggered a delete action with this delete button implemented delete button with tech helpers and then we learned something new which is using the section to render JavaScript in this case we implemented confirm delete function that internally uses the confirm JavaScript function to prevent the user from deleting the category if the user says cancel that's everything I want to cover in this video and I will see you in the next one in this video let's learn about using partial views to D duplicate code so far we have created some code duplications if you have noticed let's go to the solution Explorer and let's look at the views so we have added the added View and the app view both of them actually looks almost exactly the same at least the the form part looks almost exactly the same and that's not ideal ASP Don core provides us several ways to centralize our code so that we can remove duplications and one of the ways is called partial views and that's what we are going to use in this video and the goal is to use partial view to represent this whole part this whole form part and so that we can replace this with the partial View and also we can replace this for form part with partial view so let's go ahead and create a partial view to do that we can go under our categories folder because our partial view is not actually globally shared outside of the categories folder if we do need a partial view that is globally shared then we can put that partial view under the shared folder we can go ahead and create a partial view just add a view per normal and click on ADD now the convention is to name any partial view with a underscore just like underscore layout so let's go ahead and do underscore category and click on the add button this underscore here doesn't do anything it's just visually telling us that this is not a normal view it's a special View and in this case it's a partial view here we can remove existing code blocks we are going to use our category model class and then we can go to our edit view over here and copy this whole thing and paste it now although the added View and the ad view they look almost exactly the same there's still some differences the first place that is different is this setion in the edit view this is called edit and in the add view this is called ad and the second difference is that in the ad view here you can see we have a input field which is a hidden field to store the ID of the category so somehow in our partial view we have to be able to handle both cases that means in our partial view we have to know whether this partial view is used by the ad view or the edit and to do that we can use our controllers to pass in the information so for example let's go to L categories controller here and we have learned that this add handles the HTTP get request and this edit also handles the HTTP get request and with the HTTP get request the partial view will be loaded so therefore within this controller action method here we can provide the information and pass the information to the partial View and what we can use is something called viewback and here we can just provide anything we want because it's all Dynamic so I'm going to say there is a action variable here in the viewback and the value of the viewb is going to be edit in this case because we're trying to access the edit View and similarly over here in the ad method also going to use a review back but this time the action varibles value is going to be add we have this information then we can access the information over here in the categories partial view how do we do that we can use a c code block here and we can declare a variable which is going to be a string and we can call it action that corresponds to the viewback action variable here so if we don't don't have anything in the action variable then we can just assign an empty string to the action variable over here and now we have the information from the controller in the action variable here we can use it right here and how do we do that remember there's something called implicit expression so we can use that we can use add sign and then the action variable which is defined right over here and also we want to render this hidden field when the action variable has the value added so we're going to say action to lower equals edit and when only when this is true do we render the hidden field like this now we have dealt with the two differences right the action method name and rendering of the Hidden field here now how do we use this partial view we're going to use it in the actual view here to replace this so let's delete everything from here and now we can use a Tac Helper and this time the tack helper is not actually attribute of existing HTML element it by itself appears as a element and we can provide a name and the name is just the name of that file which is underscore category okay so underscore category and then we will need to provide the model so this model is what is bond to this particular View and we can access that at sign model and we're going to do the same thing over here in the edit view going to D duplicate by replacing this line with the partial view so name is again an a score category and we're going to pass in the model so we're going to say model equals model and that's it so now you can see that The addit View and the app view becomes very much simplified and all of the code in the view is centralized in the partial View and obviously there's so much benefit one of them is that when we need to make changes we don't have to make changes in different places okay let's give it a try just to make sure everything we have done so far still works okay let's go to our categories and let's try to add category let's do use this same name name that we used before and let's just use any anything it doesn't matter let's click on save button and it's actually working right it worked and let's click on addit and we see all of the information that means at least you know the partial view is is being rendered and let's click on uh let's change this over here to 11777 just just some random numbers and then let's click on save button and it's also being saved we can go back and verify you can see that everything is saved properly so in this video we have learned to use partial view to D duplicate and in the partial view we have learned to use the viewback to pass information from controllers and then we use the information to control what we want to render in the partial view another thing that we learned is that we learned to use the partial Tech helper to render the partial view that's everything I want to cover in this video and I will see you in the next one
Info
Channel: Frank Liu
Views: 7,181
Rating: undefined out of 5
Keywords: routing, aps.net core routing, rest api, api, web api, asp.net, asp.net core, .net, c#, visual studio, programming, tutorial, training, how to, frank liu, c# training, c# tutorial, components, data binding, architecture
Id: BzlPrVB_DwA
Channel Id: undefined
Length: 145min 31sec (8731 seconds)
Published: Fri Dec 01 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.