ASP.NET Core Razor Pages CRUD - .NET 6 Razor Pages CRUD Using Entity Framework Core and SQL Server

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi there in this video we will create an asp.net razer pages app from scratch and we will perform crud operations on a sql server database using entity framework this will be an amazing application for beginners who want to learn more about crowd operations in razer pages or if you want to refresh your memory let me take you through the app that we will build we will create a new dot and 6 application from scratch and it will be on a razor pages template on the home page we will see the list of employees we will also build a page from which we can create a new employee on adding the details we can use the submit button to create this new employee on the list page you can view and edit the details of any employee if you want to delete an employee you can use the delete button and that employee will be deleted from the database and the application takes you back to the list page if you like this video do check out my 13 hour long asp.net razer pages course that i have created on udemy that covers everything from scratch to finish it covers the basic concepts of cut operations but also uses the best practices to use led framework and using the repository pattern in this course you will use bootstrap 5 image upload functionality using a cloud platform rich text editor notifications authentication and authorization dependency injection and lot of other advanced topics of asp.net razer pages i have this on a discount for my youtube audience so check out the video description for the discount coupon with that said let's jump into this video i have created a new folder for myself and in here we will create our asp.net 6 razer pages crowd operation app and i will open visual studio 2022 using this button i will create a new project so i will click on that it takes me to the next page which from which we can select a project template we want to create a razor pages application and the second option when i see over here i have my filters as c sharp all platforms and all project types and the second option we have over here is the asp.net core web application and if you read the description it uses the razer pages framework so we will select that and click on next it takes you to the next page where you can configure your new project such as the location and the project name so we will copy the folder location and paste it here and also give it a project name i will type razer pages demo app and once you've given the name and the solution name click on next from this screen you can select the framework that you want to select for the dotnet framework so i am selecting dotnet 6 which is a long term support version and it is the latest version as the time of the recording of this video so with that selected and all the other options as is i will create the project using this create button it takes a few seconds for visual studio to create this application and we have these files that visual studio has created as part of this template looking at the structure of the files you can clearly see there's a difference to how we used to create the mvc application because we no longer see the model views and controller folders but rather we see the pages folder and if we expand on the pages folder all the pages for this web application resides in this pages folder over here for example we have the index page which also serves as the home page so we have the index.cshtml which is the razer page and holds html css and also some c-sharp stuff and the code behind us for example the on get and on post methods of this index razor page will belong to the index.cshtml.cs class which is the code behind class so this class will have the ongit and on both post methods for the index model so this is quite a page-centric approach of how we create web applications using asp.net core and we also have this program.cs file in which we are adding eraser pages to our services collection and also mapping the end points for these razer pages to our application as well so let's start this application and see what we get out of the box our application is running and we see a new website which is using bootstrap's bootstrap version 5 for the css and it's showing the top nav over here it has this body section which changes when we load a new page and it also has this footer over here so when we open the privacy page it goes to the url slash privacy and it shows the privacy information in this body section over here if we come back to the home page this is the index page that we saw inside the pages folder so if i open slash index it will open the same page so home is basically our index page so we have a new website but we want to add more pages to this website so that we can perform cred operations to the database so we will go back to the code and do some coding back into our application i've stopped the application and in here we want to use entity framework which is an orm which stands for an object relational mapping tool and we basically want to use entity framework to talk to our sql server database and it could be any database but for this example we are using a sql server database so we will use entity framework to perform crud operations on a sql server database and to use it we have to first install it to install entity framework i will right click on dependencies and open manage nuget packages in here i will go to the browse section and i would like to install these two packages the first one is microsoft dot entity framework core dot sql server so copy that and i will paste it in the browse section i will select this one from microsoft and install this once this is installed i will go on and install the second package which is microsoft dot entity framework core dot tools so i will copy this and again search in the browse section over here and select that to install it now that we have installed the packages for entity framework we want to create a db context class a db context acts as a bridge between your domain classes and the database dbcontext is the primary class that is responsible for interacting with the database back into our application i can now close the nuget package manager and in here we want to create a new class but i will first create a folder so i will right click on the project add a new folder and i will call this data inside the data folder i will create a new class so right click on data add a new class and we will name this class razor pages demo db context and click on add now we have the class ready this db context class inherits from a base class which is db context so i will inherit this from the db context class and it comes from the packages that we installed so i will control dot over here on db context and i will use this uh reference microsoft dot entity framework core so i'll add the missing reference over here now we have to create a constructor so that when we pass the options of you know the db context options from our program.cs file we pass that further down to the db context there's a shortcut available for that as well so if you click on the class name and press ctrl dot you can generate the constructor with the options parameter and that's the db context and we will populate the db context options from the program.cs class in just a moment once we have this constructor we can now define the properties that this dbcontext class will have and using those properties we will be able to communicate with the tables inside the the database in our case it will be a sql server database so we will define a new property using the shortcut prop and then press tab twice it creates a new property this property will be of type dbset and dbset further takes a type and that will be our entity or the domain model for our application so let's create the domain model i will come to the project folder right click to add a new folder here so add new folder i will call this one models so i want to create this in parallel to other folders so i will rename this to models inside the models folder i will create another folder and i will call that domain so this will hold our domain models or entities so i will create my first domain model inside this domain folder so right click add a new class and because we want to perform cred operations on employees so i will create an employee domain model so i will rename this class to employee dot cs click on add and in here we want to add a few properties to this employee domain model the first property i will add over here will be the id of this employee so i will use a good for this one which is a unique identifier and i will name this property id the next one will be the name of the employee so i can use the suggested property which is public string name and as you can see here now we have the nullable option for the project so we can say we have the nullable option as enabled so that means this name over here has to be a not null if you want to keep it as a null you have to specify it as inaudible property but in our case we want name to be not null so we will not put that question mark over there after the name property we will add another property which will be of type string and the name of the property will be email then we want to also capture the salary and display the salary so that will be of type long we can just use this as an example you can put it as a decimal as well but just for this example i'm using a long so that'll be salary after that we want to record the date of birth for the employee so that will be a date time and you can name this date of birth and finally we will have the department name so a string type and the name of the property is department so we have defined the properties for our domain model and using these properties we will fetch create update and delete the records inside the database using entity framework core now that we have our employee domain model ready we can come back to the db context and provide the employee details over here as a property so this property will be a db set of type employee domain model so let's get the missing references and it uses comes from the domain model folder so that's correct the name of the property over here will be used by entity framework migrations or ef migrations to create a new table in the database if it doesn't exist already so the name of the table we want to create will be employees [Music] and using this property we can further query or update or delete employees using entity framework so now that we have created the dbcontext class it's now time to inject this using dependency injection inside the program.cs file so that it is available to our application we will come to the program.cs file and after this this line which says builder.services.add razer pages we will add another service to our services collection so using builder and sorry this is builder dot services dot add db context and this takes a type and the type of the db context is the one that we created which is razer pages demo db context so i will type that and press ctrl dot to get the missing dependencies so using razor pages dot data so it comes from the data folder and i will open the brackets and it takes the db options builder so i will say options such that and in here i will say options dot use sql server because we want to tell the the db context to use a sql server database and also we will mention the connection string to that database so i will first write use sql server and press control dot to bring in the dependencies from microsoft core so i have the microsoft entity framework core packages and the data folder over here and to this use sql server it basically takes the uh the key or the connection string inside so we can use the connection string over here or we can get it from the app settings.json which is a best practice so let's create a connection string inside the app settings.json in my app settings i will create a new key which will be connection strings and inside the object i will create a new key again and that will be the name of the connection string i want to use for this application for this database to be in particular so we want to use the razer pages demo connection string so that is the key or the name to this connection string and in the quotes i will mention the value of the connection string so for the connection string it takes this format we need to tell it the server name we need to tell it the database information and also trusted connection is equal to true so i will copy that paste it over here and then add the missing information so i want to first mention the server name that i want to use for this project so i will open my sql server installed i have installed a local instance of sql server to my system and i also have installed this microsoft sql server management studio to query the database and servers so this is the server that i have installed and that's the name for it and i can copy it but also do confirm that you are able to connect to it and only use that name that you are able to connect it with so i'll connect it and you can see that it gets connected and i can also see the databases that i have so i will use the server name over here inside my connection string and i want to create a new database so i will mention the name of the database i want to create so i can say this will be the razer pages demo db so this will be the name that will get created inside our databases over here and you can see we don't have any database for this name razer pages demodb and that is all the information it needs so we will come back to the program.cs file and add this information so we want to give it a string of the connection string but that comes from app settings so using the builder again we will read the app settings so builder dot configuration dot get connection string and we want to specify the name of the connection string so make sure you copy the name that you have given over here inside your connection strings and paste it inside the get connection string method as an argument and make sure you have enough brackets so it's working fine so now we have created a db context class we have also created our domain model and properties so that we are able to access those tables and we also have injected this dbcontext class inside the program.cs file which utilizes the connection string defined in the app settings so we have done all the configuration work it's now to actually run entity framework core migrations so that the application can create this new database inside our sql server database so for that i will run i will go to tools and go to nuget package manager and open package manager console in here i want to execute two commands one by one so the first command i want to run is the add hyphen migration and i will come back to package manager console i will write add hyphen migration and give a space and inside double quotes i can give the name of the migration because we are creating this migration for the first time or running this migration for the first time i can give it an initial migration name so i can say this is initial migration and this name could be anything and after that i will press enter and what entity framework core is doing is it's creating a migration file so it's creating a c-sharp version of the migration so that it knows everything that it wants to execute to create this new database and the new tables inside this database so as you can see here we have a new migrations folder with a migration file called initial migration and it has everything to create this new table employees with all the information for the table and the columns inside it now we will come back to package manager console and run this migration so the command for that is update hyphen database so we will come back and say update hyphen database and it will then use this migration file to execute on the sql server database that we have using the connection string that we told the application it has completed the migration and if we come back to our database or the sql server in local instance and if i refresh the sql server we now have a new database which is the razer pages demodb and that's the same database name that we defined inside our app settings and we should have one table which is the employees and it has the columns of the same columns as we defined as properties inside our domain class so using entity framework now we can if we are able to access this employees table and we should be able to perform crud operations on this employees table let's come back to our application and now it's time to create the crud functionality that we were talking about and we will start with creating a new folder structure for the employees and we will start with creating a new employee and adding the details to the database so i will expand on the pages folder and i will create a new folder over here so right click on pages folder add a new folder and i will call this employees inside the employees folder i want to create a new razer page so right click employees add a new razer page i will use the empty template and click on add and i will call this razor page add so add dot cs html so i will create this razor page now this razor page is empty so let's just start by adding a heading to this page using the h1 tag and i will say this is the add new employee razer page and let's start our application to see if it's coming up on the screen or not our application is running but now we want to navigate to this newly created page and the way routing works in razor pages is it will map to the pages folder by default and after that i will mention the folder that i created so that was the employees folder so slash employees and then i created the razer page which was add so forward slash add and this route gets mapped to the razer page that we created so if i enter that it opens the add new employee razor page so now we have the page ready we want to create some html controls or elements on this razer page so that we can submit a form and then pass the details back to the code behind class of this razor page then use entity framework to save all these changes into the database so let's come back to our code in my add.cs html razer page i will give a margin bottom to this heading so i will specify the class of m b hyphen 3 and all the classes that i use are bootstrap classes and if you want to know more about bootstrap you can go to the bootstrap website to have a look at their documentation after the heading we will have some controls so i will use a div and i will give it a class of margin bottom hyphen 3 so that we have separation from each and every element then i will have a label for this element and the label will be the name because we want to capture a few details and if i show you the model again we have the name we have the email salary date of birth and department so we want to capture all these information from this ad page so the first one is name so the label will be called name this label will have a class which is again a bootstrap class which is form hyphen label and after the label we will have an input element so input element which is of type text now i will get rid of the name and value property attributes and we will later on use the asp handlers and sorry the asp4 attributes and define our own model properties this input element will also have a class which is the bootstrap css class and that will be form hyphen input actually it is form hyphen control and again we will specify the asp for attributes for these input elements later on but we will continue to just add the controls first so this is for the name i will copy this div and we will create one more for email this input element will be of type email so email and class would be from control again now we will have another one and let's see the model again to see what do we want we want the salary so that will be the name of salary this will be of type number and class is form control next we need a date time to add the date of birth so i will copy this and paste it one more time the label will be date of birth and the type will be date and finally we have the department which is just a string so i will copy this one more time this time the label will say department and the type will be just text and finally we need a button so that we can submit a form and we also have to create a form but let's create a button first so i will get rid of the label and input fields and i will add a button which will be of type submit and we will give it a class which is btn space btn hyphen primary or you can have a different class as well just to uh you know make it visually different the value or the text of this button would say save and now we have this form ready so i can use this hot reload feature in visual studio and if i come back i can refresh this page and now we have this form ready to be submitted to be able to submit a form inside the razer pages application we have to bind these values inside a form so i will wrap all of this inside a form element i can get rid of the action the method attribute says post which is correct and this is the form end tag so i will cut that and paste it right at the bottom even after the submit button now when this button is pressed the form that is enclosed is submitted and when the form is submitted it goes back to the on post method of this add razor page so to go to the code behind class as a shortcut you can press f7 and that toggles you between the code behind class and the razer class so we have the i add model and that only has the on get method but we also want to submit the form so that we can capture the values so we will create an on post method so public void on post now to be able to get the values from the form which is on the razer page back inside the code behind class we would need a property that binds the values and passes it back to our code behind class so we need a we need one or more values so they can we can pass the values from the form for that we would use a view model so we can create a view model inside the models folder and i will first create a folder for view models so right click on models add a new folder and i will call this i have to stop the application first so new folder and call this view models inside the view models folder i will create a class and i will call this the add employee view model and this will be the class responsible to pass the information of the form to me in the code behind class so this will have a few properties and the properties would be similar to the domain model but we don't want the id coming from the ui we will generate our own id so all we need is the information that we display on the form so we have to add these five properties to the add employee view model so we need the name we need the email salary date of birth and department and let's come back to the code behind class so we need to create a property and this property will be the the one that we created which is the add employee view model let's get the missing references from the view models folder and we can say this is the add employee request [Music] now to be able to get the values from the form we have to bind this to the form and in razor pages we get the bind attribute so in as an attribute we can say this is the bind property so we will use the bind property attribute to bind this property to the code behind to the razor page so we can now use this property inside the razer page so let's go back to the razer page using f7 and in here to all these fields we will now bind individual properties from the add employee request model so we will say for the name we will say asp hyphen for so this is the for attribute and this is for the the name of the model which is add employee request dot and you would see auto suggesting already because visual studio knows that the model that we have mentioned in the code behind class is for this razor page and this is for the name so i will say asp hyphen for name similarly for email we will say asp hyphen for the add employee request dot email we will do the same for salary so asp for add employee request dot salary for date of birth we will say asp hyphen for add employee request dot date of birth and finally we have for department so asp hyphen for add employee request dot department and now you can see why we added these five fields inside the view model and we didn't need the id because entity framework core will creates create its own id for this employee so using that in the razer page when we submit the form all these values are being passed again inside the code behind class in this property and in the on post method we can use and read this property and the values inside the property so i will put a breakpoint over here just to demonstrate and i will start my application i will navigate to the add page so employees slash ad and we have this form so let's fill up some values let's say we fill up my name and then department let's say is i t and let's save this and we have a breakpoint back inside the onpost method so it stops over there if i hover over the request over here and the property we can see that all the values that we passed inside the form from the razor page is now being captured inside this property and it's only possible because we are using this bind property attribute if we don't use this we are still able to display the values to the form but are not able to get the values from the form so this bind property is really helpful in that way now that we know we have the values of the form coming back we can use these values and create a new employee using entity framework so i will stop the application and to use entity framework we have to inject the db context so that we can use the db context class as we learned in the initial few minutes of this video that db context class acts as a bridge between entity framework and your database so i will create a constructor we're using the shortcut ctor and then press tab twice i will inject the constructor i will inject the db context inside the constructor using constructor injection so i will say the the db context is the razer pages so razer pages demo db context press ctrl dot and add the missing references i will call this db context now we need to create a private field so that we can use that private field to use it inside the onpost method but i have a shortcut over here so just click on this variable press ctrl dot and you can create and assign a field called db context now we know that the db context is being handled from the application because we injected it inside the program.cs file over here so we are getting an instance of db context which we can use inside the onget and on post method so to use the db context we first want to convert this view model into our domain model because db context only cares about the domain model so let's put a comment over here to convert viewmodel to domain model and let's do that so i will create a new employee domain model is equal to new employee and you can add the missing reference from the domain model folder and in here i will map the fields that we are getting from the view model so let's say name is equal to the add employee request dot name then we have the email which is add employee request dot email then we have the salary is equal to add employee request dot salary so i'm basically just mapping the values that we got from the form into a more readable form for the db context then we have the date of birth which is also coming from the request and finally we have the department and i will just press ctrl kd to format this so now we have converted the view model to domain model we will use this domain model and pass it to the entity framework to the database using the db context class so now we have a field which you can use so db context dot and we can access the employees table using the property that we defined so we can use the employees property and entity framework gives us a lot of methods to play around with the data so you can see we have the add method and to this add method it takes the employee entity and we have created this employee entity which is our employee domain model and we can now simply pass this into the add method like this using that we are telling the db context to add this new employee and finally to save the changes we have to just remember to use this important statement to use the dbcontext dot save changes if you don't use this line the creation of this employee or the changes to any employee won't be happening so remember to use this line after you make changes to your to your database so once that is done we can now test this functionality so i will run my application we will navigate to the employees slash add page and here we will just add the same information again and i can say just any junk information and when i press save this time i don't have a breakpoint so it will run through all these commands and save the employee in the database so i've clicked that and the page comes back to the employees ad page again so that means everything went fine and it didn't result in an exception so if i come to the database to show you if it was created or not i can now select on the employees table and previously when we had zero results in the employees table we should now have one employee created and as you can see we have that employee created with this unique identifier which is a unique grid and we have all the information correctly coming from the form and getting saved to the database now that we know our add or on post method to add a new employee is working correctly we can do a smart thing over here and we can also give a notification to the user that this was successfully added so i will create a view data for that purpose so that we can show the data back and the key for this view data would be message and the message would actually be and say employee or let's say employee created successfully and we want to show this message back to the razer page so we will come back to the add.cshtml page and inside here in the code we first want to get this string from the code behind class so when this page is loaded we will create a new message which will come from the view data and the key for the view data we know is message and if it's not null we would want to convert it to string now after the heading we want to display this success message and we will use a bootstrap alert so inside a code block we can say if and we will use string is not is not null and white space so we'll say string dot is null or white space and we will put a not operator in front of it so it's not null and not empty and not white space which is this message over here then we want to display this message so i will use a bootstrap alert class which is alert and alert success and inside this div i want to show this message that we have so add message and format this document so now it's time to run this again inside the employees add page i will again add the information let's say we have employee one and let's say employee one at email.com any information and then let's say this is h hour and then press the save button and this time we get the success message back from the application showing the user that this was successfully created so we can just confirm this back by executing this and we have employee one also created now we have created the employee successfully so we have done the create part in the crud operations it's now time to read all of these employees from the database so for that i will have to come back to the application stop it and i want to create a new page so i will close all of this we have the employees folder already defined so i want to create a new razer page which shows all the employees as a table so in here i will right click on the employees folder add a new razer page and i will use the empty template again and this time i will call this list dot cs html and click on the add button [Music] so similar to the ad page we want to first create the structure for this for this table and we will use a bootstrap table and then we will also want to pull back the details from the list dot code behind class and if i show you the code behind that's the on gate method so we will perform the uh the operation using the db context and we will get the values in the ongate method so let's first start over here let's use and inject the db context like we did in the add razor page so create a constructor for this class ctor double tab and then inject the db context over here which is the razer pages demo db context press ctrl dot to import the missing references give it a name so db context and then press ctrl dot to create and assign a private field which we can use inside the ongate method over here so using the db context we will say for the employees table that we have which is the employees property we want to get all the employees so we can do it to list and this way we are getting all the employees back from the database and we can store it in a variable so let's say this is employees is equal to this now we want to display these employees inside the uh the list raiser page over here so we can bind it to a public property over here so let's create a public property prop and that will be a list of employees as it's coming back over here so list of employees and the employees can be empty so we have to first get it from the domain model and i can mention models dot domain dot it's actually employee not employees so and the property name will be employees so now instead of creating another variable over here i can actually assign employees to it now we want to use these employees that we have and show them inside the razer page and we will first start with the structure of that razor page so i will create an h1 tag to display the heading and this will say the list of employees i will give it a class of margin bottom of three after that i will want to create a table but i want to create a table only when there's some employees so i want to check first if model dot employees is not equal to null and model dot employees dot any that means there's at least one employee only then we want to show the table so in here we will create the table else we just want to say that as a paragraph no employees found or something like that inside the if block now we will create the table and the table will have a class which is a bootstrap class of table inside the table we will have a heading so a t head tag and that will have a row with a few columns so th we will show the id we will show the name and we will show the email and that's it we will show the other details when they want to view the other details for that employee so they will press a button and then it will take them to the edit page where they can view and update the details of that employee so after the head tag we want to create the body as well and we want to loop through all these employees so i will use a for each loop so add symbol to write some c sharp code and the collection here is model dot employees and for each individual employee we want to display a row so a tr and inside the tr we will have three tds the first one for the id so i will say employee dot id so i can take this local variable and display the id for that particular employee in the loop then i will use employee dot name to display the name and finally employee dot email to display their email so we have the data coming back inside the code behind class in the ongate method once this is populated we are populating this table if this employee is not null and it has some rows so let's start our application to test this functionality in here as before we want to navigate to the list page so i will say slash employees forward slash list and this would open our list page and it is trying to fetch the data from the database and it has done that now and also displaying the list of employees inside a table now if we don't have any employees the table would not be visible and instead we will see a paragraph showing that no employees were found and you can see how easy it was to use entity framework and fetch and add or create new data inside the database on the similar approach we would create a new page which will take the the user from this page to the edit page if they want to edit or view the other details of that employee so we will add a few buttons over here for view and that will take the user to the view page so let's do that let's come back to our code stop the application and now we want to create a new page and we will call it the edit page so right click on employees add a new razer page and i will use the empty template again and create this new razer page i will name this edit we have come to the edit dot cs html page and in here we first want to accept an id and the id is for the employee that the user is trying to edit or view or delete so razer pages gives us an option to read the id from the route and we can do that using these double quotes and inside that we can ask the user to give us the id so this is the id and we can also have a type shape version of it so we can say this is a good and using that we can accept the id in the on get method so if i come back to the code behind class using f7 we can now have a grid value and the name of this parameter would be id and the name has to match what we are referencing over here and this is the route coming from the url so if i read the id over here let's put a break point over here and let's come to the list page in the list dot cs html and let's introduce another column so i'll introduce a heading let's say th and i will just put a space over there so that's an empty heading and in the column value i will say that this is a button so inside a td i want to add an anchor element and we will define the href as forward slash employees forward slash edit because it has to go to the edit page and forward slash we want to send the unique id of this employee which is here so using an ad symbol i can say employee dot id and i can change the text of this button to say this is to view or let's say edit and also give this anchor element some bootstrap classes so you can say btn let's say btn hyphen dark or something that you like so using that i will run my application and see if we are able to capture the id of that specific employee back inside the edit page the application is running and i will come to forward slash employees forward slash list to see all the employees that we have it's getting the data from the database and we see this new button called edit and if i hover over it and you see the left hand corner of this application it shows you the url that it will go to so it's going to localhost forward slash employees forward slash edit and forward slash the id of that employee which matches the id that we have in the table and if i hover over the second employee it shows the id for the second employee so using this button if i click it it comes to the edit page in the on get method and if i hover over the id over here we can see that the id is being captured of the i employee that we edited or viewed so we can use this id to get the details of the employee from the database so that we can populate the form so let's do that now i will stop the application and i will first use the db context to search the database for this employee so i will say uh i will create a constructor ctor double tab and in here i will inject my db context so razor pages demo db context press control dot to import the missing references and then name it db context press control dot again to create and assign this private field now we will come to the on get method and use this db context to go to the employees and we can find it because this is a unique identifier of that table and it's also the primary key we can use the find method given to us by entity framework core and we can pass the id of this employee this will give us a response back so let's capture this response so we can say employee is equal to whatever is coming back from the database after that we will check if the employee coming back is some value or it's null so we can say if employee is not null then we want to transform this into a view model so let's say we have to convert domain model to viewmodel and in here we will create another view model so right click on this view models folder add a new class and i will call this edit employee view model in the edit employee view model you want to get all the properties from the id to the department so i will copy all the ids or copy all the properties from the employee domain model and paste it inside the edit employee view model now we don't want to edit the id but we would need the id so that we could fetch the employees details and update the correct employees details so i will get rid of the spaces over here and we are using the view model so that our domain is separate to the views so our domain can change but our views are not dependent on our domain so that gives us a separation of concern as well so we will convert this so i can say where this is the edit employee view model is equal to new edit employee view model let's get this from the view models folder and in here we want to map all the fields and all the values from the domain to the view model so let's say id is equal to employee dot id then the name is equal to employee dot name email is equal to employee dot email then the date of birth then comes the salary and finally we have the department now we have mapped all these fields into a view model it's now time to return this or present this to our razor page and for that we will again use a public property so i will create a public property so prop and this will be of type view model so edit employee view model and i can call this edit employee viewmodel now we will populate this property using what we had over here so i can replace this local variable into this so we are populating this public property over here and finally we are returning the view now that we have the edit employee view model populated we can come back to the razor page which is the edit.cshtml and in here we can define the html structure that will update the values of the existing employee onto this form so let's first start with a h1 tag and we will give it a class of margin bottom hyphen 3 and this will be edit employee so we can say edit or view employee or something similar then we will have a div similar to how we did in the add razor page so i can come to the add eraser page dot cs html and copy all of these over here so let's just copy one and we will change it accordingly so i will replace this div and we have a label that is to be used for the id first so let's say id that has a class of form hyphen label the input is of type text and class is form hyphen control and the asp4 value is form for coming from the edit model so if we come back to the code behind class we have to use this the bind property attribute as we did in the add razor page so if i say bind property now we can display the values back inside the form and the elements and also receive the updated values from the form back to the code behind class so now i can say edit employee view model dot id and we don't want the id to change so we can say this is a read only field after that we will create one for name so i can change the label to say name again type of text and this will be for name i can remove the read-only attribute from this one because we want the user to be able to change it so i will copy this a few more times i will change it to email have the type of email and asp4 is edit employee view model dot email copy it one more time for salary so salary is of type number and it's coming from the salary property inside the edit employee view model then we have the date of birth which is the label changes to date of birth the type is date and then this is for the date of birth property finally we need another string for the uh for the department so i'm copying the name that's department that's type of text and then the property is for the department finally we will have a button so at div with the class of margin bottom hyphen 3 i will create a button so that we can use it to submit so type is equal to submit the class is btn bt and hyphen primary you can have a different color if you want to and the text of this button would say update or edit or something like that now we need to add a form that when you click this button it submits a form so even outside the h1 tag i will create a form element i can take off the action attribute and take the form ending tag and put it right at the bottom after the button so when the button is clicked it will submit this form with all the values that we have inside the form and it will come to the edit model page and we'll come to the on post method which we will create now so we will have a on post method so public void on post and it will basically utilize this bind property uh the probably public property that we have and we'll use the values from it so here similar to how we did in the ad we want to convert this view model to domain model so we will say where employee is equal to new employee or we can say models dot domain dot employee and then we want to say the id is equal to the id that is coming in which is from this property then the name is equal to this dot name email is equal to this dot email salary then we have the date of birth and finally the department and after that we will use the db context to update this so first of all we want to find if the if the details are not null so the form has some value so even before converting it we will check if or we can just straight away say let's say if this view model is not equal to null and this dot id or let's say just not null and then inside the if block we will try to search for this employee and using the same approach how we did over here using the find method we will say dbcontext dot uh employees dot find and we can pass the unique identifier because we know this is not null we can say this dot id and we will store it in a variable we'll say this is an existing employee we will then check if existing employee is not equal to null that means we found the employee then we will go on and convert this viewmodel to domain model so i have taken everything inside that if block over here now we can update the instead of creating a new employee we can actually ex i mean we can actually update the existing employees details so we can get rid of these two lines and this line and actually update the existing employee dot properties so i used the alt i pressed the alt and then selected all the rows to be able to edit faster so i can now change this to semicolons instead of commas and we are now updating the employee but we don't want to update the id so let's remove that because we want to keep the id as is so we are updating the name email salary date of birth and department after that we want to save these changes so entity framework is tracking these changes but we want to save it to the database so we will say dbcontext dot save changes and using that we should be able to update this employee so it's time to test it and let's do that let's start our application we have the application running and i will navigate to forward slash employees forward slash list and using one the edit button i will let's say edit this employee and change the name from employee one to employee two so let's edit that it comes to the on get method i can now take away the breakpoint and it displays the details of that employee in you know in the form and let's change the details so let's say this is employee 2 and even change the email change the salary to add another dollar and let's say change the date to november and change the department as well just so that we know all the fields are getting updated so let's click on the update button and that reloaded the page so if we come back to the employees list page we will be able to check that out so let's forward slash let's go to forward slash employees forward slash list and now this employee has changed to employee 2 email has changed and if i edit to view other details the details have changed as well so now we can do a similar thing on the razer page and create a notification or an alert when this is successful so i can say view data and the view data key is message when this is successful give me the message that employee updated successfully and using that we have given a message now we have to check it inside the edit page so in the add block you can say well message is equal to we will read the view data from the key message if it's not null convert it to string and now we can use this message after the h1 tag let's say if string is null or white space and we want to invert it so i'll put a not in that we are checking the message string if that's not null that means we have a message we want to use the bootstrap alert so i div with the class of alert and alert success and i want to put the message in here using the add symbol so add message now i will hot reload the application will come back to it and reload this one more time now with a change let's say i change it to employee 3 and updated i can now see the green success message over here now finally we have added a new employee we have read its details and read the details of all the employees it's now time to delete an employee so we will add a button over here which will delete the employee so let's come back and stop the application in the edit cs html which is our razer page i will come down to the bottom and we have this div which contains one button i will add another button and that will be of type submit as well and the class will be btn btn hyphen danger which is a button with a color of red and i will name this button or have the value as delete now we have two buttons but we only have one form to submit so i will also add a class so that we can have a separation in these two buttons so i will give this div a class of d hyphen flex using it as a flexbox and then justify content to be between so we have space between these two buttons so as i was saying we have two buttons but we only have one form to submit we want to basically submit this form into different methods back inside the code behind class currently we only have one which is the on post method but we want to submit the delete button as well we want to click the delete button to submit this form again so that we can delete that employee for that razer pages has a the asp handler attribute so asp hyphen handler so asp page handler is equal to and we can specify what handler it will be so i can specify the word delete over here and how this will work is it will come to a method if it exists so i will create a method public void and the method would be on post and now the handler name which is delete so the delete button when clicked will come to the on post delete method and now we also can change this on post method to say this is the asp hyphen page handler for the edit or update let's say this is update so the update button goes to the update handler and the delete button goes to the delete handler so i will change this old on post method to say on post update and the keyword of the handler should match the handler name over here so now we have two methods one is on post update which is still working or it should be working we will test that and the new one is on post delete where we can use this id to delete this employee so let's say let's imagine this is working now i want to find this employee first so i will copy that row again and using the db context i can say employees dot find and now we will use the edit employee dot id because we are submitting the form and i can say this is an existing employee i will say if existing employee is not equal to null that means we found the employee then we want to delete it so we can say dpcontext dot employees dot remove which is the remove method and it can remove the employee so we can pass the whole employee object into this remove method and that will remove the employee for us but make sure you save the changes afterwards so db context dot save changes and with that we we have implemented the delete functionality as well and because the delete would have been successful here we want to redirect the user back to the list page because the user doesn't exist anymore we want to say we want to redirect it back but we can't do it with a void so we have to change this void method into an i action result and now we can say return redirect to action or redirect to page because that's a different page redirect to page and now we can say the page give the page name and we will say the page name is forward slash employees forward slash list to go to the list page and if the delete doesn't happen we can just go back to the same page again so we can say return the view or return the page in this case because we are using razer pages so with that we have the on post delete method as well and it's time to test it so i will run the application the application is running i want to go to forward slash employees forward slash list and let's say i want to delete the employee over here which is employee 3 so i will go on and use the edit button to view or update the fields but if i want to delete the field i can use this button but because we changed the update method let's quickly test that again so i will update the department and make sure it's working so you can see update was successful and now if i go back to the page let's say i remove this handler it's changed to hr and it's now time to test the date functionality so i will click this button and because the delete was successful it redirected the user back to the employees list page where you can now only see a single employee here and if i come to the database and execute this again we only have one employee left so the delete was successful now our crowd operations were successful i hope you enjoyed this video and if you did please press the like button and also subscribe to the channel and i also have the full course on razer pages on udemy so make sure you do check out the description of the course in the video description below i hope you have a wonderful day thank you for watching and i will see you in the next one
Info
Channel: Sameer Saini
Views: 13,784
Rating: undefined out of 5
Keywords: asp.net core razor pages crud, asp.net core razor pages, asp.net core razor pages tutorial, asp.net core razor, razor pages, asp.net core razor pages the complete guide (.net 6), asp.net core razor tutorial, asp.net razor pages crud, razor pages tutorial, razor pages crud, razor pages in asp.net core, asp.net, asp.net web application tutorial, crud operations in asp.net core
Id: ZEwVdAxdzys
Channel Id: undefined
Length: 77min 44sec (4664 seconds)
Published: Tue Sep 13 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.