Asp.Net Core MVC CRUD Operations with EF Core

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
quick demo of this tutorial here we are going to implement correct operations insert update and delete in latest asp.net core mvc using entity framework same topic is discussed three years back it won't work as it is because of the new updates in the framework this topic is discussed with best practices that i have learned so far and in this video i have discussed the solutions to most common problems or issues that you might have while developing this application there are a lot of things to learn from this video so definitely this will worth your time so please watch till the end of this video so here is my visual studio 2022 now let's create a new project now select the asp.net mvc template in c sharp which i can see inside this recent project templates here if you can't see we can do this from this language drop down select c sharp then under this project types select web now you could easily see the template asp.net core web app model view controller in c-sharp language so this is the template that we are looking for now click on next now name this project here in order to demonstrate correct operations inside this mvc application we'll be using bank transactions so i will name this application as bank transaction now select the location where you want to save this project make sure that there is no special characters inside this folder path directory here it might cause unexpected errors in various stages of the app development i had similar experience in past so if there is any special characters inside these folders here consider renaming them appropriately now let's go ahead with the project creation for this project i'm using the latest.net 6 version i will uncheck this https configuration since you're having this project only for the demonstration now let's create the project so here we have the brand new asp.net core mvc application before going forward i would like to give you a brief introduction to this asp.net core application here so this project is built on.net core inside that we have this asp.net core framework for building this mvc application now let's get familiar with the important directories inside this project first of all we have this www root it consists of static files like stylesheet javascript files and and inside this library folder we will be having ui frameworks like bootstrap or any other libraries and here we have the icon for this application and here we have the mvc part model view controller we'll be discussing each of them in depth throughout this tutorial now this json file app settings contains the configuration details for this application like db connection string finally we have program.cs5 which is the starting point for the execution of this application in previous version of asp.net go along with program.cs we had a file startup.css where we have done the most of the configuration for the application but in latest versions we don't have such a file so we'll be configuring everything inside this program.says file here if you are using a previous version of asp.net code with startup file i'll be showing the alternatives on startup.cs file don't worry about that here you could see a web application builder is created from this builder instance the service for mvc is added and thereby this application became an mvc application without this functioning vocation here this would be a plain console c-sharp application and here we have started the build operation for this application and here we have configured how do we want to show the error message if there is any based on whether we are in development environment or not you could customize accessing static files from this application with this function invocation here and with this method we are configuring the routing for this application if you need any authorization you can customize this method here and here we have the default routing configuration for this application so the first part of the url after the base url will be the controller name which by default is home which you can see inside this controllers folder and the next part will be the action name which is index and any query parameter after that will be considered as the id parameter you can see that in a bit so this is default routing for this application at last with this method invocation run the application will be compiled and opened in our default web browser to run this application we have two modes with and without debug mode so i will go for this without debug mode here so this is how the fresh mvc application looks like before going further i want to show you the popular accessing asp.net core mvc tutorials from this channel most probably you are already looking for best tutorials in these topics so first of all use authentication operations like user registration and login are implemented with asp.net core identity here and here we have the second video if you want to know how to upload and retrieve images in asp.net core mvc and here we have this special video the same correct operations from this tutorial is implemented in mvc as a single page application using jquery ajax with single page applications we can avoid reloading off pages in between i have given the links to these videos and more videos in video description and inside the first comment of this video now as i mentioned already in this asp.net mvc application we are going to implement the correct operations using entity framework core for that first of all we have to install corresponding and new get packages so right click on this project here then manage and you get packages inside this browse tab search for ndd framework code so here we have the package microsoft entity free vocal now from this version drop down here select the same version as that of this asp.net core here to see the framework version right click on it then select properties so here we have the version so select the same version from this drop down here now click on install accept the license so here we have successfully installed the package along with this package we have to install these two packages microsoft entity framework called tools and since we are using sql server db for this application we have to install this package also so select the same version as that of the entity framework call from this drop down here now let's install the sql server package so here we have successfully installed these three entity framework packages now it's time to create a model class for the transaction entity for that let's add a c sharp file here transaction now let's add the corresponding properties one by one first of all we have the id property transaction id account number beneficiary name bank name then we have the swift code or ifsc code then we have the amount finally the date of the transaction now we want to make this transaction id property as the primary key so i will set this key attribute here to add the corresponding namespace you can use the shortcut hold ctrl then press period now add this namespace data annotations now you could see the green squiggly line for these string properties saying we have to make them as nullable or either we have to initialize them inside the constructor of this class we'll always be initializing these properties in appropriate places so just ignore this line or you could suppress this issue here just hover the mouse on the property then you could see this downward arrow click on it then suppress for now let's suppress this issue like this as you know this class indicate an entity framework model we'll be creating the physical table corresponding to this model through migration so once we do that the corresponding columns for these string properties will be having n boxcap max data type which is more than what we need so we have to explicitly mention the data type for these properties accordingly for that we can make use of this attribute column let's add the corresponding namespace so that we can do this type name is equal to invoke then specify the number of characters that we need for these properties here for account number i will set it as 12. now let's do the same for rest of the string properties i will search nvoc 100 for both bank name and beneficiary expecting maximum 11 characters for swift code internationally so here we have done with the model clause let's create a db contest class with that let's add a new c-sharp class file called transaction db context now we have to inherit this class from the entity framework called clause db context now let's add the corresponding namespace using the shortcut hold ctrl then press period or dot simple add this namespace entity framework code now we need a constructor for this class for that we can make use of this snippet ctor then double tap so here we have the constructor for the clause for this constructor class we need a constructor parameter of the type dbcontext options which is of the type transactiondb context i will name this parameter as options and we have to pass the same parameter to the base constructor so we can do this base and let's pass the same parameter here options you will understand the need of this db context options parameter for this constructor in a bit while explaining the dependency injection once we create our mvc controller for now just keep it as it is so during the migration this transaction db context defines or manages what are we need in the physical db after the migration so in order to create a table corresponding to this transaction model here we need a property connecting to the transaction model inside this db context class here for that we'll be creating a property of the type db set like this db set of the type transaction model now we'll name this property as transactions so after creating the physical db the corresponding table for this model will be named as transactions you will see that in a bit now we have to go for the dependency injection of this db context class i will do that inside this program.css inside this latest version but if you are using an old version of asp.net core you have to do that in startup.cs file so let's look how we can do the dependency injection and i will be explaining how this dependency injection works once we create a control inside this application okay now if you are using a previous version of asp.net code with startup.css file like this you have to do this dependency injection inside this method configure services calling adddb contacts method from the services of the type i service collection okay to do the dependency injection we can make use of this builder instance here so let's do the dependency injection for the context builder dot services dot add db context method can be called and here we have to specify the db context class transaction db context let's add the corresponding model namespace so with this dependency injection we are going to create an instance of transactiondb context now actually for this class we have the constructor here so here we have the constructor and this constructor is expecting a parameter of the type db context options so it should contain the db connection string along with the db provider so with db provider we are telling which type of database we are using in this application we will be using sql server or sql server we can have other databases also like mysql postgresql etc so based on the database you are using the corresponding db provider should be passed to this constructor parameter here so let's pass this parameter value options while doing the dependency injection here for that i will be using this lambda expression with options so here we go options dot use sql server function can be called in order to use this db provider we have to add this namespace entity framework code now inside this method we have to pass the connection string for the db so first of all we'll be saving that inside this app settings.json file here connection strings inside that i will be saving the connection string with this name dev connection now here we need to provide the db connection string if you don't know how to generate the connection string for your database or sql server instance you can look through these articles here this is from srishab corner and here we have the official msdn documentation i have given these links in video description you can go through them for now we'll be pasting the db connection string template like this so first of all we have server or you could also use this name data source meaning we have to provide the sql server address and its instance name here so local in my case the sequel server instance is installed on my system itself so i will be specifying it as local here and the and the name of the instance is sql express in order to check the install sql server instance you can do this first of all open drain for that you can use the shortcut hold windows key then r then type services.msc it will open up a window with all the services installed on your system search for sql server so here it is sql server so here we have the name of the instance in parent this is sql server express that's what we have mentioned here now make sure that this service is already running if it is not in running state instead of these options you could see a start option now back to the connection string here after server we have database so here we have to provide the name of the database it would be transaction db so this db is not the inside the sql server here it will be created through migration okay instead of this database we can also use this keyword initial catalog data source or server then database or initial catalog then we have to provide the credentials to access the sql server instance actually there are two ways to do that in my case it is installed on my system itself so i can use the windows authentication itself for that we just need to set this attribute trusted connection as true if windows authentication is not available it will be only available if the sql server instance is installed on your system itself if windows authentication is not possible you have to provide user id and password install configured while installing the sql server instance in order to execute multiple queries in a batch we have set this attribute multiple active result sets as true or you could say mars mass so this is how we specify connection string now let's pass this connection string to this method use sql server for that we can make use of this builder object like this get connection string method can be called and here we have to specify the name of the connection string which is dev connection now we have done everything for the migration so let's do the migration before that we have to build this project so right click on the solution then build solution after successful build open package manager console in my case it's already here package manager console if you can't see the package manager console though select the project from the solution explorer like this then go to tools and you get package manager then package manager console now for the migration first of all we have to execute this command add migration the name this migration something like initial create execute as a result of this command execution here we have a new folder migrations inside that we'll be having the c sharp code corresponding to create the actual physical db based on our given model here now in order to create the actual physical db we have to execute these migration codes here with that we have to execute another command update database so here we have successfully completed with the migration for some of you you might be getting this error mainly there are two reasons for this error first of all the sequel server instance is not in running state so make sure that it is in running state from this services window here and the second reason is that this connection string is here is not given in proper format or the credentials or the sql server instance address is not correct in order to verify that first of all you can open the tool of your choice for managing the database from visual studio itself you can use server explorer for connecting to the db in my case i will be using sql server management studio or sms here then try to connect the sql server instance with the same details that we have given inside this db connection string here i am using this instance here and i'm using windows authentication if you are using sql server authentication you have to select that from this drop down and then provide the username and password here if you are able to connect with the instance with the given details here then the problem is in the generated connection string here then check the correctness of the connection string with these articles given in video description okay if you find it difficult let me know in comment box below now let's connect with the db now if you expand databases node here you could see the new db transaction db as per we have given inside this connection string here inside that you could see a table corresponding to this model clause here so here we have the db let's expand it so here we have the table transactions now let's check its design so here we have the table and its columns created as per our db model here now back to the project now it's time to create an mvc controller for this transaction model here for that right click on this controllers folder then add controller now from this left panel here select controller under mvc now select this template mvc controller with views using entity framework click on add as a model i will select this transaction model here and here we have the db context transaction db context we want to generate the view reference script libraries use layout page will be discussing that in a bit and i will name this controller as transaction controller click on add as you can see here this scaffolding mechanism here automatically installs the and you get package code generation for some of you there might be some problems while creating your first mvc controller in a project for the first time most of the time it is related to installing the code generation package in this project the transaction controller is created without any problem we'll be discussing what is inside this mvc controller in a bit before that i want to address this problem related to installing this package here code generation this one here now if you get such an error go to the and you get package manager for that right click on this project then click on manage and you get packages now you can search for the package code generation here now this is the package that i'm talking about code generation design you can check the package here if it is not present inside these packages here you have to install that from this package manager here in some cases you will get the error related to installing this package code generation design even though the package is listed under installed packages here you will get the error in that cases you can uninstall and then install it again meaning you have to reinstall the package again to get rid of the error okay now let me close this package manager here now let me collapse these dependencies here and let's focus on this controller transaction controller now this transaction controller is created using scaffolding mechanism meaning we have provided the model for this control and the db contacts we are using and thereby it creates action methods of the tab get and post and its corresponding views are added to this views folder here under this views folder you could see a new folder with the same name as that of the created controller inside that we have the views required for each of the action methods here we'll be discussing each of them in a bit before that i want to discuss about dependency injection that we have discussed before so here we have the controller transaction controller which is inherited from the framework class controller and here we have the corresponding controller constructor it has a single parameter transaction db context now how does this constructor get the value for this constructor parameter of c type db context that's for dependency injection comes into the picture inside the program.cs file we have added the dependency injection for the db contacts here so basically this statement here creates an instance of this clause transaction db context into that we have to pass the connection string and the db provider that we have passed here so this will create a complete instance of this transaction db context and this created instance will be patched to the constructor of the controllers which has a constructor parameter of the type transaction db context so all the parameters having a constructor with the same parameter transaction db context the value or instance of this parameter will be passed from this dependency injection here we don't have to separately create an instance inside these controllers here actually inside an mvc application we are not manually creating an instance of this transaction controller here whenever we make a request into this controller the framework automatically create an instance of this controller at that time the constructor will be called and the value for this parameter of the type db context will be passed from this dependency injection here now inside this constructor the instance from the dependency injection is assigned to this private property of c type transaction db context and this private object is used in rest of the controller in order to interact with the db so hope you understood how dependency injection works in asp.net mvc applications now back to the browser the application is already running here in order to reflect the new changes inside this application we have to build this project again in latest version of mvc application you could see the progress of the build inside this icon here once the build is successful the application will get reloaded automatically now let's navigate into this index method of this transaction controller for that let's check the existing routing configuration here first of all we have to provide the controller by default which is home then action by default is index if there is any id parameter we can pass that at the end like this in order to access the transaction index method we could do this transaction but as per the routing configuration the default action method is index so we don't have to provide that inside this url here forward slash transaction is enough so this is the view from our index action method of the transaction controller so here we have the action method inside that it is returning the view so here is the corresponding view index.cshtml the same name of this action method will be used for the corresponding view here see cshtml view here is responsible for this view here this table is rendered from this html here okay if you're frequently watching our latest videos knows that i always recommend dark mode in order to avoid eye strains from these white screens here especially if you are watching this video in night time you will get a lot of eye strains because of the brightness from these white colors in order to avoid that in this web browser i'm using this extension here dark reader so i'm going to enable dark mode inside this application it definitely reduced a lot of eye strains from these white screens here so let me enable this dark mode if you want to have a similar experience you can install this chrome extension dark reader like in my case here and you can use this extension in any web application which does not have the dark mode by default now let's talk about the layout page inside this index field here there is nothing related to layout page but if you expand this shared folder here you could see the layout page here so this is the layout page it works as a parent view for rest of the views inside the application basically inside this view we have the html wrapper for all of the views inside the application the html declaration with head and body tag is is rendered from this layout page and the content from these views is rendered in place of this at render body okay for all the views inside this application this shared view or layout page will be used as a parent view this now bar is rendered from this layout page here if you want to verify that you can set this layout as empty string let's build this project now back to the application only the html from this index view is rendered because we have disabled the layout page now let me get rid of this line here now inside this layout page head reference you could see the bootstrap reference here along with this bootstrap for developing this application i want to use phone awesome icons so let me grab phone over some cd and reference so let's search for that here normally i use the reference from this website cdnjs.com so for this application i'm using this version here and i will copy this all dot mean dot css reference let me copy the tag and pasting inside this head reference let me save this and back to this index field now before customizing this index view let's start with this create new view which is responsible for creating new transactions so this url here forward slash transaction forward slash create is invoking this action method here create so let's start from this action method itself by default it is returning the view with the same name as that of this create here so basically it is returning this create view here now the controller that we have created with this scaffolding mechanism has different methods like or action methods like create edit delete and details and same in case of these views here create or insert operation and update operation is handled with separate views and separate actions you could see the create get and post action methods here and here we have the corresponding view and here we have the edit view and you could see the corresponding get and post action methods here now in order to avoid the overhead of keeping them as separate i'm gonna merge them into one action method add or edit so first of all i will rename this get create action method as add or edit i will do the same rename operation for this create view here add or edit so the corresponding url will be like this transaction forward slash add or edit now from this get action method will be returning this view add or edit and into that model we just need to pass a fresh instance of the transaction model so i will do this new transaction model so here we have the instance which is passed to this view add or edit and which is accessed with this model here now let's build the solution back to the application now let's change this url action method name here to add or edit first of all you could see the title here create bank transaction which is coming from this view data here view data title inside that we have save the create instead of that i will pass transaction so this view data is used inside this layout page here see the title for this page is set here the view data that we have set from our child views is appended with the name of the application here so here we have the updated title now let's customize this view as per our requirement first of all i want to center everything from the child views for that inside this layout page here we can use the bootstrap grid system like this but that we can do this everything inside this div will be using eight columns from the git system and we need an offset of two columns so offset md2 now let's move this render body to this div here now let me remove this create title here as you can see this form is wrapped within this div with the four columns instead of that we need six columns and then we need an offset of four columns now let's move this title into this div here now inside this form you could see a pair of label and input text box field for each of the properties inside the model class that we have defined first for inside this form we don't need this date input controls is the date of transaction that we can pass from our code itself so first of all i'll remove that from here now these labels are the exact property name from our model process instead of that we want to customize the label name for that we can make use of this attribute display name so i want to show the corresponding label like this in between account and number we need a space like this and we have to import the corresponding name space here now let's do the same forest of the model properties here now the labels corresponding to these two properties amount and date will be shown as it is so it's fine let's build this project and back to the application so here we have the updated labels now i want to show the text boxes for this swift code and amount in a single line for that we could do this first of all we'll be having the div with class row inside that we have two divs with six columns each now let's move this swift code into this first half here now the amount controls into the second half after each modification build the project and then back to the application now let me change this title from h4 to h1 so here we have the title h1 and we don't need this horizontal line let me remove that so here we have the div called md6 and we want to change this offset to call md3 so 3 plus 6 plus 3 gives 12 columns now let's customize this submit button here first of all i want to change the button text as submit and i want to show this hyperlink along with this submit button here for that we can do the same like we have done for this swift code and amount controls here so we need a raw div and two columns with same width so let me copy this and pasting here now let me copy paste this for the hyperlink and here we have the clause tip for the row now let me move this submit button into this first column now let's move this hyperlink to this second column here now actually this hyperlink is navigating the index action method which is returning all of the transactions inside the db so i will rename this hyperlink text as view all meaning view all transactions now i want to show this like a bootstrap button so i will copy this class from here and pasting here instead of btn primary we need bt and secondary so here we have those two buttons first of all we need a top margin we can have this class m means margin empty means top margin of the range 2. now i want to expand these buttons in available space here for that we can have this bootstrap class with 100 now let me copy this and pasting for this view all button now if you click on this view all button here it will be navigating the index action method which is showing all of the transactions inside the db so here we have the index view currently there is no transaction inside the db so the table is empty now if you click on this create new button it should navigate the add or edit view right but actually it is navigating the create action method it was the previous name so let's modify that inside this index view now in order to navigate through open tabs here you can use the shortcut hold ctrl then press tab then keep pressing tab until you reach the tab that you want to open so in this case we have to open this view index so release the hold key now let's change this action to add or edit back to the previous view which is the index action method or index view now let's reload the view now let's try the hyperlink here it's working perfectly fine now let's implement validation inside the form here that we can do inside the transaction model actually inside this form everything is mandatory or required for submitting this form so we could do this we'll be specifying the required validation with this attribute required now we'll copy paste this for rest of the properties so here we have specified required validation for the properties now let's build the project back to the application now if you try to submit this form here you will get the validation errors like this we'll be customizing this error message in a bit before that i want to talk about how this validation is working okay as i mentioned already this layout view here is working as a wrapper or a parent view for all of the views inside the application and inside this layout.css html we have these script files loaded just before the body end tag like this along with that you could see a render section for scripts meaning child views can make use of this script section to load scripts in this place here for example inside this view add or edit you could see this script section so this script section is passing this partial view here you can see the same inside this views here inside this shared folder here we have the partial view validation script partial if you open that you could see few script files which are corresponding to jquery validation it is present inside this ww root under this library folder here we have the jquery validation script files actually these script files are used for client-side script validation okay so this partial view is rendered inside this section and the scripts inside these sections will be replaced in place of this layout script section here okay that's how scripts are loaded into the layout page from the child views in this case we have these script files corresponding to jquery validation these are libraries used for client-side validation meaning this validation is done at run time you don't have to submit this form to the server it will be done at the client side itself because of jquery validation scripts you can check that here currently this account number is not valid and here you can see the corresponding error message once we start typing inside this controller here the error message goes if you remove everything inside the controller you can see the corresponding error message like this so this is what we call client-side validation so this same validation will be done at server side also let me show you that here so here we have the transaction controller and this form here is returned from this get action method add or edit and here we have the view and here we have the form this form will be submitted to this action method create actually i want to rename this to add or edit okay now we have to rename the corresponding post action method here so here we have the post action method create let's rename it to add or edit so the form posted from this view here will be submitted or posted to this action method inside the action method you could see this if clause checking whether this received model is valid or not as per our requirement so validation is done at both server side and client side for example assume that for some reason the client side validation is not working in that case the error will be caught at the server side here okay so by default validation on both end is done by default in mvc applications now let's look how to customize these error messages here that to this required attribute we can specify the error message like this this field is required now let me copy paste the same forest of the required properties now inside these input text boxes account number and this swift code i want to limit the number of inputs with that we can make use of the attribute max length so for this account number maximum we can have 12 characters and here we have the corresponding error message now let me copy paste this for swift code for swift code we can have maximum 11 characters let's build the project and back to the application now let's submit the form without entering any data see here we have change the error messages for the validation now if you click inside this text field you could see the previously posted data from a similar form so in order to avoid this you can set the attribute of the form autocomplete as of so here we have the form and let's set this attribute or reset this attribute autocomplete as off since we have set maximum number of characters for these two feeds we can't enter more than 12 characters inside this field here see and same for this swift code also so validation is working properly fine now this form is ready to submit the data into this post action method here add or edit now let's start modifying this post action method now first of all in order to access this pose action method the corresponding url will be like this transaction forward slash add or edit before going forward i want to make this transaction controller as the default controller so go to program.cs file here and let's change this to transaction here now back to the post action method here now once we submit the form the data from these form controls can be received with this action method parameter transaction here first of all we'll verify the validation of the properties inside the model now here we have i write the object transaction object from the model into the db context and this save changes method will insert the corresponding record into the transaction table after all will be redirected to the index action method here it will return a view to display the existing transactions inside the table so that's all about this pose action method and here we have the last return view statement and this will be executed if the validation fails meaning the return transaction model will be having the accessing data that we have sent from the model and along with that we'll be having the error messages as per our model now before this insert operation we have to feed the date of transaction into this date property here so i will do this transaction.date is equal to datetime.now okay that's enough for now let's make a new transaction now let's submit the form boom that's it so here we are redirected back to the index view and here we have the newly inserted transaction you could see the same inside this transaction table here let's execute this select query here so here we have the corresponding record so all of these columns are populated with the corresponding field data now before going forward let's customize this index view here this index view is returned from the index action method of the controller here so here we have the index action method inside this action but the index view is returned into that a list of existing transactions is passed so here we have the index view and here we have the past list of transactions inside the model and list of transactions are displayed within a table here and here you could see the for each loop to iterate through the list of transactions now inside this table first of all remove unwanted columns from this table so which are bank name and swift code so we have to remove corresponding address cell and body cell so here we have the header cell now let's remove the corresponding body cell also now let's show this date column before this amount column here with that we just need to change the order in both body part and the header part okay and i want to change this header to something like list of transactions or i will set it as something like passbook now i want to move this create new hyperlink to the last column header cell here so here we have the hyperlink let me cut this and let's get rid of this paragraph here and here we have the last column header and let's paste the same here now let me apply bootstrap classes first of all we have btn class bdnsm and let's apply a green background so btn success now along with this text here i want to show a phone awesome icon for that go to this website phone over some dot com forward slash icons now the search for this icon plus i will select this first icon here now if you click on this i tag corresponding code will be copied to the clipboard and we just need to paste that here inside this hyperlink i just want to show this text new so this is how it looks like now if you want to make a new transaction you can click on this button here corresponding transaction form will be displayed like this now you can go back to the list of transactions with this button we all now inside this date transaction column here i want to format this days trick that inside this transaction model we just need to add a new attribute for the property date so here it is display format into that we can pass this data format string and here we go we need to display the month in three digits so mmm then we have two digits for day and two days for year now it should do the job now as we have shown here we have to deal with update and delete operation we don't need this details hyperlink here so first of all let's get rid of that so here we have the hyperlink let me get rid of this details hyperlink now we have to implement both these editor update operation and this delete operation so next we are going to implement the edit or update operation inside this hyperlink instead of this text edit i want to show a phone awesome icon like this corresponding to a pen now let's apply some bootstrap classes btn then bdn hyphen warning now here we have the action method edit and here we have the id parameter passed with this transaction id now let's check that inside this transaction controller here actually here we have the uh edit action method of the type get like i mentioned before both insert and update operation will be done with this add or edit get and post action method so let me get rid of this edit get method and edit post action method and we don't need this get details action method here now let's remove the corresponding view files also now we'll be handling the get request for update operation inside this action method add or edit so i will change this hyperlink action method to add or edit now back to the action method add or edit here we are already returning a view for insert operation containing a form for insert operation now we also need to return a form for the update operation but that we can have this id parameter here and by default i will set this value as 0 so for insert operation we won't be passing an id parameter for example inside this create new hyperlink here we are not passing any id parameter here with this hyperlink so the id parameter will be having the value 0 but in case of this update operation here we'll be passing a non-zero id value for the update operation like this here okay so based on the value of the id parameter we can say whether we have an insert or update operation so i will do this we'll be having this if clause if id is equal to 0 will be returning a fresh form for the new transaction if there is a non-zero value inside the id we can handle that inside this else part here now we just need to copy this return statement from here and let's paste that here now instead of passing a fresh transaction instance for update operation we have to pass an existing transaction for the given id for that we could do this here we have the db context inside that we have the list of transactions from that we just need to call this function find and here we just need to pass the id so this will return the corresponding transaction record and it will be passed to the view which is this add or edit view here now rest of the things can be handled inside this view here now we want to make few modifications inside this view in order to incorporate update operation inside this same form we have already implemented the insert operation now before doing that let's verify the working of this get action method for update operation here so build the project back to the application now if you click on this edit button here it should make a get request to this add or edit action method here let's try that boom that's it so here we have the get request url that we have just made with the hyperlink and it returns a transaction form populated with the corresponding transaction details for this transaction id here now after making required changes to this form we can submit the form for updating the details as you already know this form will be submitted to this action method add or edit off the type post inside that we have already handled the insert operation now we also need to handle update operation also before that i want to make few changes inside this form appearance here i want to switch this label text and this button text to uppercase for that we can make use of the global css file which is though inside this www root css folder here so here it is side dot css so at the end i will be adding this custom css here we will transform the text case to uppercase for label text and the button text of the type submit along with this i want to change the color of the label to create so i will do that here color is equal to gray changes inside this style sheet does not need a rebuild of this project it will be reflected immediately inside this project here now let's implement the update operation with this action method here in order to check whether we have an insert or update operation we can check the transaction id if it is equal to 0 we can say we have an insert operation in that case we have to update this date to current date and then we have to add the model into the context if we have an update operation we can handle that inside this else part here we just need to call the update method so let me copy this and pasting here instead of this add method we just need to call this update independent of whether we have an insert or update operation at the end we just need to call this save changes method here now we have to be careful about one thing inside this get action method for the update operation we have returned the view with the existing transaction details now when we submit the same from this form here corresponding properties with the updated values will be submitted to this action method here but here we are missing something inside this form we don't have form controls for properties like transaction id and the date of transaction so when we submit this form the properties like transaction id and date won't be reached up to this post action method here so the value of transaction id and date will be null in order to avoid this problem we can add hidden fields for such properties so i will do this we can add hidden fields like this input of the type hidden this is for transaction id so we can do this asp for transaction id like this we need one more hidden piece so let me duplicate this and this time we have a date hidden field so this hidden fields will be having the values that we have passed from this get action method here the same value will be reached inside this post action method when we submit the form so everything is ready for the update operation let's build this project back to the application let's make visible updates inside these form controls to make sure that update operation is working for all of these fields here now let's submit the form boom that's it so you could see the updated values here if you want to verify that you can go to this management studio re-execute the select query here that's it next we are going to implement delete operation before that let me add two more transactions here now let's do this delete operation here that back to the transaction controller for delete operation we have two action methods here one of the type get and other is post and here we have the corresponding view for delete operation in order to simplify this process i will be removing this delete view here in our previous tutorial we don't have this post action method we have done the delete operation inside this delete get action method and one of our friend is race this question is indeed unsafe to delete requests using get action methods it's actually unsafe if we implement the delete operation with get action methods we can delete our course by making a get request like this we just need to enter the url here like this if the delete operation is implemented within this get action method delete and the corresponding record will be deleted so it's not a best practice to implement delete operations with get action methods so in this tutorial we are going to implement delete operation with a post action method we can't make post requests from directly entering the url here it can be only made with a form submit event so that's what we are going to do here so first of all i'm going to add a form element here inside that i will add a button of the type submit now inside this button instead of a text i will be showing this phone over awesome icon for a trash bin now let me assign few bootstrap classes here bdn then bdn danger now let's specify the action method so we could do that with this attribute asp action so it will be delete along with that we have to pass the transaction id through this id parameter like this here so let me copy this from this hyperlink and pasting here now we don't need this delete hyperlink let me remove that from here now back to the transaction controller we'll implement the delete operation with this post delete action method here so let me remove this get delete action method here so here we have the method delete confirmed and here we have set the route or action name as delete so in order to make the request into this action method we have to use this url here so that's what we have specified inside this form here inside this form we only have one single button for the delete operation now this action method already contains the code for delete operation we don't need this method transaction exists let me remove that from here so here we have the action method for delete operation first of all we will find the transaction with the given id and we will remove the item from the db set transactions and finally we just need to call this method save changes and finally we will be redirected to the index view to show the updated list of transactions now back to the index view again boom so here we have the submit button for the delete operation don't worry about the orientation of this button we'll fix that in a bit so as soon as we click this button delete button the pos action method will be invoked before that we want to make a confirmation from user site because delete is a lot of data so before actually executing the operation we'll ask for user confirmation for that we can implement this on click event here inside that we could do this we'll call this javascript method confirm inside that will ask this question are you sure to delete this record so this will prompt a dialog if user confirm the operation with yes then this function will return true and then the form submit event will be triggered so this is the best practice to implement delete operations with post action methods now before actually testing this delete operation here i want to make the proper arrangement of these buttons here i want to show these two buttons in a single line for that for that first of all i will move this edit hyperlink to this form here now in order to align them in the same draw you can make use of the bootstrap button group you could see the similar examples here for that we just need to wrap these two buttons with a div like this class is equal to btn group now in order to set smaller size for these buttons we can add this class btn group sm finally before testing the delete operation i want to shrink the width allocated for this table here so back to the index view first of all we need a div with the class row inside that we can have this div allocating eight columns from the grid and offset of two columns now let's try to delete this record here that you can click on this delete icon here and here we have the confirmation are you sure to delete this record so if i cancel this confirmation nothing will happen if you confirm the operation boom that's it the list of transaction is refreshed so that's it guys here we have implemented insert update and delete with asp.net go mvc latest version 6 using entity framework or db force approach i have given the github repository link for this project in video description you can either download or clone the project from the given repository if you found this video helpful please consider subscribing to this channel called affection if you haven't yet please like and share this video with your friends and colleagues so that they can also benefit from this have a nice day see you in next video
Info
Channel: CodAffection
Views: 168,034
Rating: undefined out of 5
Keywords: CodAffection, Asp.Net Core MVC Tutorial, Entity Framework Core Code First Approach, Asp.Net Core Web App Tutorial, Asp.Net Core Insert Update and Delete in EF Core, .Net Core Tutorial, Get started with Asp.Net Core Application, Asp.net Core Beginners Tutorial, asp.net core, entity framework core, code first approach in entity framework asp.net core
Id: VYmsoCWjvM4
Channel Id: undefined
Length: 55min 25sec (3325 seconds)
Published: Mon Apr 04 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.