ASP.NET Core Web API CRUD with Angular 11

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
quick demo of this video tutorial here we will implement asp.net core web api cred operations with angular 11 using entity framework core and sql server this is the final output of this project inside that we have implemented operations like insert update delete and retrieve on payment details like credit card or debit card to insert a new record fill up this form here three digit security code and finally the expiry month and year inside this form we have implemented proper validation to each of these form controls here now submit the form so here we have successfully inserted card details of steve list of card details is refreshed to fetch newly inserted code here if you want to update a record select the row from this list then corresponding details will be populated inside this form here now let me update this owner name here submit the form corresponding record is updated you could see the updated name here to remove an existing record click on this trash icon from this last column then confirm the operation that's it we have deleted the corresponding record from this application since we built this whole project from scratch you could learn a lot and you could apply the same in a future project i am sure you will find this tutorial helpful for your upcoming angular and asp.net core projects so please watch till the end of this video hi all welcome to quarter fiction in this video we will implement asp.net core web api credit operations with angular we have already discussed the same with all versions of the frameworks which was in angular 7 and asp.net code 2.2 if you try the same with latest versions of this framework it won't work as expected so i decided to make that video again with latest questions angular11 and asp.net core 5.0 in parallel to this video tutorial i have a text article on the same topic link is given in video description where i would try my best to update the content with future versions of these frameworks before starting this video i would like to thank for your paypal donations for my previous works in order to make more helpful and quality tutorials like this you can also support me through paypal or other payment methods details are given in video description now without further ado let's get started with the topic as always first of all we will be creating an asp.net web api project before getting into that i want to clarify few doubts that you may have regarding latest.net 5.0 if you want to skip this section and start creating the web api you could jump to the timestamp given here the previous versions of the framework are named as dot net core then the version number like 1.0 1.1 2.0 and then the last major release was dot net core 3.1 but as a next major release after dot net core 3.1 we have dot net core 5.0 you may have some doubts like i had when i heard of this release it is named as dotnet 5.0 why it's not.net core 4.0 it is already mentioned in this article while explaining new changes and updates in dot net 5. i have given this article link in video description we name this release dotnet 5.0 instead of dotnet core 4.0 for two reasons we skip the version numbers 4.x to avoid confusion with dotnet framework for point x before dotnet framework we have been using this platform dotnet framework the major difference between them is that dot net core is cross platform and the old platform dotnet framework is only specific to windows operating system so the majority of those release versions start with four to avoid the confusion with these versions here they skip the version four so that explain five point or here now the second reason explained dropping the word core from the latest release name which is to emphasize that this is the main implementation of dotnet going forward dotnet 5 supports more type of apps and more platforms than dotnetcore.net framework so the upcoming versions of the framework will be named as dotnet6.net7.net8 and so on even though the word core is dropped from dotnet 5 subframe works asp.net core5 and entity framework 5 retains the name code to avoid confusion with all versions of those subframe works that means in this tutorial we will be working with asp.net core 5 and nad framework core 5. also donate 5 comes with c sharp 9. if you want to know new changes and updates in dot net 5 you could check this article later i have given the link in video description now let's create the web api in asp.net code file so here is my visual studio 2019 in order to work with dot net 5 i have updated the ide to the latest version here and in order to update the ide i have used this application here visual studio installer okay now let's select this project template here asp.net core web application with this option selected from these top drop downs here you could easily find the template here now click on next to demonstrate cred operations we will be dealing with payment details of a customer so i will name this project as payment api now select the location where you want to save this project click on create now select asp.net core web api now make sure this from these top drop downs here we have selected dot net core and asp.net core file for now you don't need this https configuration since we are working in a development environment if you want you can enable this option also and finally here we have open api support this is optional with this we can test our web api methods so i will enable this option here now click on create so here is the brand new web api project when it comes to asp.net core5 there is nothing major difference from previous version so let's get started with the project development as i mentioned already we are going to implement credit operations on payment details of a customer so first of all we will be creating a model for the entity for that let's create a new folder add new folder models inside that let's add a model class payment detail so first of all here we have the primary key which is payment detail id now we have to mark this property as primary key with this attribute key now we have to add the corresponding using statement up here for that you can use this shortcut place the cursor on the attribute then hold ctrl then press speed now select the appropriate using statement here now we can add rest of the properties card on a name card number expiration date and finally security code since we are creating model class for entity framework core once we migrate this into a actual physical db columns corresponding to these string properties will have the data type and work max which is more than what we need for these properties here so let's specify the column data type separately so we can use this attribute column we have to add the corresponding namespace so use the shortcut hold ctrl then press pd type name is equal to n work 100 now let me copy paste this for remaining properties here and work as 16 assuming that internationally card number can have maximum up to 16 characters and then we have expiration date for that we have five characters so it will be of the type m forward slash yy okay so maximum we need five characters here and finally we have the security code so that i will set three characters here so here we have the payment detail model now with this model class defined here we can create our db context class as you know in nad framework db context class decide what should be created in physical db through migration so in order to create a table for this model clause here we have to have a property corresponding to this clause in our db context class so let's create that db context clause here i will name it as payment detail context first of all we have to inherit this class from entity framework base class db context before that we have to install entity framework call into this web api project here for that right click on this project here then manage and you get packages from this browse tab search for entity framework code now let's install this package here microsoft entity framework code now from this version drop down select the same version as that of asp.net core click on install accept the license once you install a package successfully you could see this green icon next to it now we have to install two more packages entity framework or sql server select the same version click on install and finally we have to install this package also entity framework call tools select the same version click on install so here we have successfully added entity framework core into asp.net web api now back to the db context clause here now let's add the corresponding using statement with the shortcut hold ctrl then press period microsoft entity framework now we have to add constructor for this class for that you can use this snippet ctor then hit tab now let's add the parameter for this constructor here so db context options of the type same class payment detail context as options we will explain this parameter later for now let's complete this function definition here now along with this constructor we also have to call the base class constructor so we can do this into that we have to pass the same parameter options now let's add a property for this model clause that we have created here payment detail so here we have the property db set of the type payment detail model clause so i will name this clause as payment details so with this property added here after migration there will be a table corresponding to this model payment detail now let's talk about this constructor parameter here db context options into this parameter we have to pass two informations database provider it can be sql server mysql postgresql etc and then database connection string with the database name that we want to create through migration as you know a class constructor parameter will be passed when corresponding class instance is created in asp.net core we can make use of dependency injection for creating db context class so we will do the dependency injection in startup clause here don't freak out if you don't know how dependency injection works i will explain everything once we create a control inside this project for now from this startup class configure services method will be passing value for this constructor parameter db context options through dependency injection so first of all we can do this services dot add db context function can be called into that we have to pass the type of db contacts here so payment detail context now let's add the corresponding model namespace here now inside this function we can pass the constructor parameter here with this arrow function options options from options parameter we can call this function use sql server now let's add the corresponding namespace now by calling this function here we have specified sql server as a db provider now into this function we have to pass corresponding db connection string now first therefore we have to save the db connection string inside this json file here app settings so i will add a new item here connection strings with this name dev connection for now i will paste the connection string here so for this project i will be using this local sql server instance here and here we will be assigning a new db payment detail db since we are using local authentication i have set this property trusted connection as true in order to execute multiple query batches we have set this property multiple active result sets as true now let's pass that connection string inside this function here for that we can make use of this configuration of the type i configuration here so we just need to do this configuration dot get connection string function can be called into that we have to pass the connection string that we have saved here so the connection now we have done everything for our database now we can do the migration with this tv context and the model clause here migration is the process of creating physical db with the model and context defined here so first of all we have to build this project here to make sure there is no error inside this application so far once you build the project successfully you could see the success message in bottom left corner here now to execute migration commands we have to open package manager console in my ide here it's already here package manager console at the bottom panel if you can't see package manager console here select the project from solution explorer then go to tools and you get package manager then package manager console now first of all we have to create a migration for that we can execute this command here at migration now let's provide a name for this migration something or like initial create hit enter as a result of the command execution you could see a new folder migrations with corresponding c sharp file here inside this newly created c sharp file it has c sharp code for creating actual physical db we have not yet created a db with this command we just created this file to execute this file we have to execute one more command here so which is update hyphen database hit enter now the update command is executed successfully now let's check whether it created a physical db or not for that here is my management studio let's connect with the local server expand databases node so here is our new db payment detail db inside that we should have a table corresponding to our model clause so here it is payment details so inside this sql server table we have columns corresponding to these model properties here first of all here we have the primary key payment detail id and rest of the columns are created as per our model class now with this column selected go to column properties here let's expand identity specification inside that you could see this is identity set as yes which means we don't have to insert value into this payment detail id column sql server will take care of that it will start from 1 and increment it by 1 upon new record insertion now back to the web api project here now let's create a web api controller with necessary web methods for payment detail credit operations for that right click on controllers then add controller now from left panel select api now select this scaffold item api controller with actions using entity framework click on add model class will be payment detail now select the db context class that we have just created i will name this controller as payment detail controller click on add some of you may get this error while creating the api controller no need to freak out we just need to install this a new get package microsoft visual studio web code generation design and just try again so click on ok let's cancel this then right click on this project here manage and you get packages within this search box just search for this package code generation dot utils you only have to install this package if you have an error like i had here click on install accept the license once it is done close this indicate package manager then let's try again add controller api with actions using entity framework payment details and payment detail context controller will be payment detail controller click on add boom that's it as a result of scaffolding mechanism here we have the payment detail controller with all of the web methods required for the credit operations we will look into that in a bit before that let's talk about this controller constructor and dependency injection as you know this payment detail controller is a class c sharp normal c sharp class which is inherited from this controller-based class from asp.net core as you can see here an instance of this controller class will be created by asp.net core when we make an http request into these web methods in need this constructor has a parameter of the type payment detail context which is saved into a private property here and thereby rest of your methods inside this controller can make use of that context db context object to interact with the db through entity framework now from where do we pass the value for this parameter context of the type db context that's for the dependency injection comes we have already defined the dependency injection inside startup.cs here we have already defined dependency injection for the db context inside this startup class by calling this function add db context so an instance of this db context class will be created by passing its constructor parameter as mentioned here db provider with corresponding db connection string whenever an instance of api controller is created and if it's constructor has a parameter of the type db context that instance will be shared from this dependency injection here so that we can focus on rest of the web methods here now let's look how these methods works and how we can make use of them from our client side application for that first of all let me run this application here without debugging so once we run our api you could see an interface looks like this here you could see all of the endpoints or controllers and its web methods that we can make use of now inside this we have the web methods that we can make use of from our payment detail controller we have this user interface here since we have selected the option for open api support while creating the project now let's make a get request so click on this get section here click on try it out now parameters needed for this web method click on execute so here is the response an empty array now let's look what we have inside this web method here so here we have the url that we have made api forward slash payment detail as mentioned inside this startup class here the routing for this application is left to corresponding controllers here so the controller is already defined its routing structure api forward slash controller so api forward slash payment detail and here we have made the get request with this web method here we will retrieve all of the records that we have inside the db table on payment details for now we don't have any row inside this table so that explains this empty array here in ndt framework list of requests from a table can be accessed with corresponding db set property which is here payment details and finally to convert that into a list we have called this function to list async now after this get request let's try this um post request here with which we can insert a new record so here it is let me close this let's make a post request click on try it out for this post web method we have a parameter of the type payment detail model through which we can pass values for the new object to be added so with this json format selected from here i'm gonna pass a new object here number is specified with this data type and work at 60. so maximum we can have 16 characters here now expiration date month then last two digits from the expiry year then security code before this open api support we were using postman now with this swagger ui here we can test our api from our application itself click on execute boom so here we have the response 200 meaning request when successful as a result of the request we have inserted a new object and that is returned as a response here with the newly inserted id or primary key now let's check that inside this table here let me execute this query again boom so here it is so inside this post web method here we have passed the object with this parameter and with the help of entity framework to insert error code we just need to call this add method from the corresponding dbset property that we have defined here and finally we just need to call this function save changes and thereby the corresponding sql queries will be executed in backend so that new record will be inserted into the table here and that's how this record is inserted into the table here finally with this return statement here it will return the newly inserted object we will explain how this works in a bit back to the api here inside this request body we have sent this json object since we are receiving this json object with this model property here payment detail these json properties are in camel casing and that of this model is in pascal casing hope you know what is meant by pascal casing and camel casing in camel casing all of the words first letter will be uppercased except the first word here in pascal casing all of the words first letter will be uppercased as per the naming convention in c sharp applications i have named these class properties in pascal casing while in case of client-side applications angular react or javascript language or json according to their naming convention properties are named in camel casing how do these properties bind to corresponding properties inside this model here we don't have to convert this camel casing into pascal casing while receiving the object it's already done by the asp.net core the reverse happens when we receive data from the api you could check that with this get request here let's execute this again now it returns the one object that we have just created you could see that all of these properties are returned in camel casing it's done by the api itself now it's not mandatory to follow any of these naming convention in any of these frameworks whether it is asp.net core or the einstein application angular or react you could name these properties in camel casing and thereby you are using camel casing on both side in that case you have to disable the default conversion that's already there inside this asp.net code for that you have to update this startup function configure services like i have mentioned inside the article here with these codes here i have given the link of this article in video description but as a best practice shisha developers follow pascal casing for class property naming now back to the post web api method here finally from this web api method this function is called created at action it will return a status code to node 1. it means a new object is created in server side you could see the same under server response to node1 and the new object is returned from this statement so with these two parameters here this function will create an url for the newly created object you could see that here so with this url we can retrieve the same object that we have received let me copy this and pasting here we can call that from this browser tab directly so here it is we have made a get request and it returns the corresponding object so here we have the web method that we have just invoked with this request here get payment detailed we have already discussed this first get method which is to return all of the requests inside the tablet and with this web method we will return a specific record with the given id here for that we will call this find function from the db set if there is an object for the given id it will be written here if it's not the f4 not for not found error will be returned so we have called this web api method with the url here which is written as a response of the post request here and which is made possible because of this uh function here created at action it will return the newly created object url along with the newly created object now we have two more web methods we have discussed these three web methods now let's talk about this put method here which is to update a given record that request will reach up to this method here put so the corresponding url will be of the format like this that id will be received with this parameter id here and with this payment detail parameter we can receive the updated new object so first of all it will compare the id from this parameter and the id inside this object id it will be the inside this property payment detail as the primary key if they match each other we just need to set the state of this model property as modified and finally just call the save changes function now there is a possibility for this concurrency exception that is handled inside this cache block here suppose this application is used by a wide range of users there is a possibility of deleting or modifying same the code by multiple users that situation is called concurrency it can be handled in different ways it's a topic for another discussion you could check out this msdn article here i have given the link in video description it explained how you can deal with concurrency conflicts in entity framework core if you end up inside this if else block here the record or data that you are going to work with is already deleted by someone else so it will return this error for not for not found else it will draw this exception if you really want to know this concurrency exception in detail please check out that article if we try to explain that here this video will be even longer we can discuss that in another video finally if the update operation is successful it will return this response no content let's try that here let's make this put request click on try it out we are going to update this record with the id one so we will pass one here now here we have to pass the object with updated details for now i will just copy that from here and then i will paste the same here these two properties these two properties should match each other so i will pass the same value here one now let's make some modifications here [Applause] now click on execute boo so here it is from this work method here we have returned no content so there is nothing to look for inside this response now let's check whether the record is updated or not let me execute this again boo so you could see the modifications here now finally let's try this delete operation here click on try it out we are going to delete this record here so id will be one click on execute let's check that here inside the table it's deleted so here is the corresponding wbbi method delete so this id parameter we will receive the id that we have passed while making this request and with that it will find the corresponding record and saved into this payment detail variable here if it's not null we will remove that from the table by calling this our function remove and finally we just need to call this save changes function after any of the operations insert update or delete and finally like we have done inside the update operation or web method we will call this no content method without any modification in any of these web methods we can do the basic red operations based on your logic of implementation you may need to modify these web methods on a practical project you could do that once you learn the basic credit operations here we have a solid web api project implemented all of the correct operations now let's look how we can make use of these web methods from our angular project now let's create a client-side app in angular 11 inside the same folder where we have already created our web api project in order to work with latest versions of angular we just need to update angular cli for that i have been using these two commands one by one in order to uninstall existing angular cli first of all we can execute this command here and then to install the latest version we can execute this npm command here i have given this stack overflow link in video description you could check that from there also now let's create an angular 11 project here for that first of all we have to open command prompt from the same folder directory for that you can use this shortcut here inside this folder path just type cmd then hit enter so here we have opened the command prompt from the same folder directory as that of this folder here to create an angular project you could do this ng new the name of the application for now i will name it as payment app hit enter while creating the application it may ask questions like this to configure the app further in this case it asks for whether we want to enforce strict type checking and strict bundle budgets we could discuss that in this application later for now i want to enforce strict type checking so i will choose y for yes so that we can reduce runtime errors hit enter would you like to add routing no which style sheet format would you like to use i will stick with css hit enter currently it is installing some default npm packages into this application it may take a while based on your internet speed so please be patient finally we have created the app successfully we will develop this application in vs code editor and while we have the web api in visual studio i have chosen this ide combination based on your suggestions from our previous community port now in order to open newly created angular app in vs code editor first of all we have to navigate inside the application folder which is already created here payment app so cd payment app to open this folder in vs code editor you could do this code space period hit enter so here we have the brand new ankula 11 project before doing anything first of all let's run this application for that let's open a terminal from this ide here then you could execute this angular cli command ng serve this will compile and run this application from localhost and in order to open the same app from our default web browser you could add this flag o hit enter would you like to share anonymous usage data about this project with angular team no hit enter so this is how the default view of a fresh angular application now let's start customizing as per our requirement so back to the vs code editor here most of the development will be there inside this src folder here so here we have the index.html which is the root html file for the entire application inside that we have the basic html declaration with head and body part inside the body you could see this tag for the component default component app so here is the app component inside that you could see this typescript file for the component where we have this selector app root with that selector here we have the tag with open and closed tag so this will be replaced with this component html file here app component html which is here so this html file is responsible for the default view of the application here now let's start customizing this app as per our requirement before that i want to show the structure of the application that we want to build here so let me create a new file here app structure dot txt i have already prepared this structure for now i will paste that here so here we have the root file src so inside that we have this app folder here as we have mentioned inside this application we will be dealing with payment details of a customer so inside this application basically we will be having two components the parent component payment details it will be created inside this app folder here so here we have the parent component payment details and here we have the child component payment detail 4. inside this component here we will design a form for the credit operation and inside this parent component we will list all of your course that we have already inserted and there will be a separate folder shared for saving service and model class for payment detail for designing this app we will be using bootstrap stylesheet and for icons corresponding statute reference will be added into this uh root html file index.html now let's create these components here for that let me open one more terminal to create an angular component you could execute this command ng g4 generate c4 component the name of the component which is payment details so let me copy paste that here for the single component payment details it will create these four files this is for the typescript file where we have the component definition and inside this html we will design the component here we have the component specific style sheet where we can add css trues specific to this component finally here we have the test file with the extension spec.ts which is for test purpose inside this application we don't need this component specific stylesheet and this uh test file for these two components we have to skip these two files this style sheet file and this test file we just need to do this in order to skip the component specific style sheet we can add this flag here s and to skip this test file here we could do this skip test hit enter so here we have the new component payment details with corresponding html and typescript files now let's create its style component payment detail form for that we just need to modify previous command since we are going to create this new component as a child component to this one here we can do this parent component forward slash the name of the child component okay hit enter so here we have the child component payment detail form with corresponding html and typescript file while creating these html and typescript file at the same time the appmodule.ts file is also updated as you can see here so here it is appmodule.js file inside an ankula application everything is organized into modules different modules by default inside an angular application there will be a default module which is this app module here so corresponding to this app module we have this folder app inside that we have created all of our new component and also this default component app so in order to make use of these components that we have just created we also have to add the same into this declarations array so both of our new components are already added into these array declarations here since we have created it through our ankula cli here now we have to create two more classes here they are these model and service classes so first of all let me create this service class here we will use this service class in order to interact with the web api that we have created before so ng g4 generate s4 service we have to create this service class inside a new folder shared so shared forward slash payment detail for a service class file we just need to skip this test file with the extension spec.ts in order to skip the test file we could do this skip tests hit enter so here we have the service class within this shared folder now inside this same folder shade we have to create this model class here unfortunately there is no specific command for creating a model class in angular cli even though we could do the job with class creation command so here is our previous command ng for generate instead of a service clause we have to create a class file and the name of the class will be same as that of the service class payment detail now it's recommended to name model class files like this dot model.ts in order to have this extension dot model we can use this flag here type so double hyphen type is equal to model so here is our angular cli command for creating our model payment detail sorry type is equal to model hit enter so here we have the new file paymentdetail.model.ts for our model class payment detail now we have created all of the component required for our application here now let's start developing this application first of all let me add a stat sheet reference for both of these bootstrap and phone awesome icons so first of all go to the official website for bootstrap getbootstrap.com click on get started now let's copy this statute reference now let's paste that inside this index.html here i will do that just about this head n tag now like this we have to add cd and reference for phone awesome icons so let's search for cd and phone ourselves most of the time i will copy the cdn reference from this website here cdnjs.com now let's copy this link tag for phone awesome all dot min.cs file now let's paste that just about this head and tag now back to this model clause here now let's add required properties like we have added inside this web api model here first of all let's enter into zen mode which is a feature in vs code editor so that we can hide every panel except the current editing file in order to search for the future zen mode first of all you could do this ctrl shift p and search for zen mode you can click on this option to enter into zen mode or you can use this shortcut here i like this mode because there is no distraction so first of all we have the property payment detail id corresponding to the primary key that we have here inside the web api model as we have discussed before the asp.net core will convert these pascal case properties into camel case when we retrieve the data and when we send the data the camel case json will be converted into pascal when we submit data from this angular project here we will be passing data through camel case properties when it reached up to this asp.net core web api here it will be automatically converted into corresponding pascal case and it will be binded to this corresponding property here now we have to specify the type of this uh property here now you could see this red squiggly line here it says the property has no initializer and is not definitely assigned in constructor this error is shown here because of the forced stick mode that we have already configured while creating this angular application enforcing the strict mode is helpful for reducing runtime errors but we don't need this rule this specific rule here now let's look how to remove or ignore this specific stick rule here for that first of all we have to open the file explorer you can use the shortcut hold ctrl then press b all of the configuration that we have done while creating this application is stored inside this file here ts config.js now in order to ignore this specific rule here we will reset this property here strict property initialization as false now the error is gone now to hide this explorer use the shortcut control b now let's add rest of the properties here card on a name as string card number expiration date security code now here we have the model class now let me open the explorer now let's design a form for the correct operation with payment details that we can do inside this style component here so here is the corresponding typescript file and here is the corresponding html file first of all let me create a property of the type model clause inside this service clause here here is the property form data offset type payment detail which is our model clause click on this auto suggestion here it will automatically add the import statement at the top now let's initialize that with a new instance of the model class payment detail hi guys how you doing i'm coming here after completing the whole project recording here i want to make a correction here i was expecting this new instance of payment detail will return an object containing all of its properties with the default values that's what happens in c sharp this number will have the value 0 and all of these string will have the default value empty string that will be happening in c sharp but here in typescript that's not the case if we create an instance of the class like this with a new keyword it will retain an empty object like this instead of that we need an object of payment detail with all of these properties with the default values for that we have two options either we have to create a separate constructor like this inside that we have to initialize these properties one by one like this like this we have to initialize rest of the properties so it is little bit annoying so i will just remove this constructor instead of that we can initialize these properties while declaring them so all of the string properties will be initialized with empty string now inside this form data we will have a new object of payment detail with the default values now while showing this model class in rest of this video you won't be seeing this uh initialization here because i have made this correction after completing this whole project recording now you can continue with the rest of the video now using this property form data of the type payment detail model class we can design a form inside this component html file here for that first of all we have to inject the service class inside this typescript file here so we could do this public service which is offset type payment detail service so this dependency injection is also similar to the baby pi dependency injection whenever an instance of this component is created an instance of service class will be passed or shared into this constructor property here now with this service clause we can access this form data that we have created here since we have created this property inside this service class we can share the same with other components also because this service class instance will be injected or this instance will be shared among all of the other components so the changes that we have done from this child component can be accessed from this parent component here payment details now back to the child component using this injected service property we can design the form here first of all let me get rid of this default html from here form now first of all i will add a hidden field for this primary key here payment detail id so here it is input type is equal to hidden for input controls we have to set the name property i will set it as payment detail id now let's set the value for this control here that we can pass from this model class property form data of the type payment detail so we will do this service dot form data we have injected the service class instance inside that we have the property form data of the type model clause inside that we have payment detail id now for the rest of the properties we will add this div with this bootstrap class form group instead of typing this manually you could use this emit abbreviation here first of all type the html element that we want to add and then after this period simple we can provide the name of the class form group then hit tab boom this is a simple application of emit abbreviation you could create multiple html elements like this with a single abbreviation later if you have time please do check out how you can make use of emmett abbreviations inside that we need a label so with emmett abbreviation we could do this just type label then hit tab we don't need this for attribute here so i will just remove that from here card owner name now we need a text box so we could do this input and we have to add these classes from bootstrap so form hyphen control then we need one more clause so we could do this form control lg hit tab so here we have the input control with those two classes form control and form control lg we don't have to specify the type of this control as text separately by default it is text so i will just remove that from here now here we have the placeholder as full name for all of the input controls we have to specify the uh name attribute so on card name all of the visible controls inside this form will be binded to this model class properties through two-way data binding in order to do that first of all we have to have this reference for the control card i'll just copy this card on a name and we will assign that with ng model and then here is our two-way data binding ng model is equal to we will assign the respective property like we have done for this hidden field here so service dot form data dot card on a name like this let's add rest of the input controls for rest of the model properties so i will just copy paste this div here let me modify this label here card number placeholder will be 16 digit card number now we have to update this name property and this two-way data binding here now you could use the shortcut hold ctrl then press d it will select the next occurrence of the word so hold ctrl then press d so here we have selected two card on a name now let's do that once again so we have selected all of the card owner name that we want to update now let's type card number like this let's add rest of the form controls let me copy this and pasting that below twice for security code and expiration date so first of all we have security code instead of showing entered characters into this field i will show them as dots or bullets for that you can set this type as password now let's set the placeholder now let's update these attributes of properties and finally we have the expiration date so label will be valid through inside the placeholder i will enter the format of expiration date mm forward slash yy now let's update these attributes and corresponding properties expiration date now let me exit from the zen mode for that hit escape twice currently we are showing the default component inside our application here instead of that let's show our newly created components payment detail and its child component so here is the uh default component app component.html let's get rid of these default html elements from here and inside that i will add this div with this uh bootstrap class container inside that we will show this parent component payment details so here is the corresponding typescript file in order to show this component we can use the selector app hyphen payment hyphen details so let me copy this inside this html here we just need to create a tag for the selector now to create a tag for this selector you can use the shortcut just retype this last character here yes then press tab now this parent component html payment details dot component.html will be shown instead of this default paragraph we want to show this child component html payment detail form in order to show this html we want to create a tag for this component selector so let's add a selector for the child component first of all we will have the uh module name by default we have app module the name of the component which is payment hyphen detail so here we have the embed abbreviation shown in auto suggestion hit tab so corresponding tag will be added so inside this parent component we have shown the child component and inside this app component html we have shown this parent component payment details now this component selector will be replaced with its corresponding html file here since we have used two-way data binding here we have to add corresponding module inside this appmodule.ts file here so first of all we have to add the corresponding impost statement here from ankula forward slash forms we have to import forms module now let's add the same inside this imports array here now let me save all of these modifications and back to the application here boom so this is how the form looks like for some of you you may not be seeing this form here you will be having some errors showing here or here inside the terminal where we have run our application while developing this application we might be making major errors inside the application it will block from recompiling this application and that's the reason for not showing the form like this here in that case you could restart the server first of all in order to stop the server you could use the shortcut control c then type y for yes then execute the command again ng serve dash o still if this terminal showing some errors that we have already cleared before like the strict enforcement we can relaunch this window or ide for that you can use the shortcut ctrl shift p then type reload window then click on this option here it will relaunch this ide with the same project it will remove all of the chaos that caused the project from running previously if you still have some problem let me know in comment box below if there is any valid error showing inside this terminal you have to fix that first okay so here we have the payment detail 4. this form is stretched to the end with of the application we can fix that later for now i want to show these two controls in a same line both security code and expiration date for that back to the vs code editor here for that we can add this div with this class form draw now let's enclose these two form group divs with this new div here so let me cut this div and tag here and pasting that here now we have enclosed both of these form groups within this form draw here now both of these divs will be shown in a single draw in order to divide them into two halves we can add this class here called md six let's add the same class to the second div here so here we have shown both of these input controls into two halves in a same line now before moving forward i want to show a title for this page here that we can show inside this parent component here payment details so before this child component i will add this uh element from bootstrap jumbotron we can use this uh component for showing titles for an application inside that i will add this uh h1 element with these classes display four and one more class text sender to align this text in sender horizontally inside that we can show this payment detail register sorry here we have a typo jumbotron let me save this back to the application so this is how it looks like by default this element has extra padding vertically so in order to avoid that we can use this uh spacing helper class from bootstrap padding horizontally we will set that of the range three maximum we can set it to the range five now let me save this back to the application that's enough now let's avoid stretching this form here for that we will add a bootstrap grid system with two columns inside the first column we will be showing this form here and inside the second half we will show a list of insert order codes later now in order to add the bootstrap grid system with a met abbreviation you could do this first of all we need a div with this class raw and inside that we need do with this class called md6 like this we need two divs inside this div here multiply by two now hit tab that's it so here we have the outer draw div and inside that we have two columns with call md6 now let's move this form into this div here paste the cursor on this line then hold alt then use the upward arrow to move the line upward and inside this second column here we will show list of our payment details later so the first column we have shown the form and later we will be showing a table with inserted records now in order to style these form controls here let me add some css rules that i have already prepared so i will paste that into this style sheet here styles.css okay this styles.css is the global style sheet for this angular application now let me save this and back to the application here now currently values inside these form controls are showing from the uh service property form data through data binding so here is the property form data from this service class of the type payment detail we have initialized that with a fresh instance of the clause here now we are going to implement validation inside this form here so first of all i want to disable default html validation for that we just need to add this attribute here no validate so i'm going to implement validation inside these controls like all of these field should be mandatory or required before submitting this form here before that we forgot to add the submit button into the form so let's do that and then we will deal with the validation so back to the form and here let's add another do with this class form group inside that we need to add this button with these classes btn then btn info in order to enlarge this button we can add this class bt and lg and finally btn block to extend this class within this outer form group div here now hit tab type of this button will be um submit button text will be submit now we want to implement the validation like this all of these input controls are required in order to submit this form here so required validation will be applied to all of these four controls and then number of characters inside these input controls are limited here it should be 16 characters and here it will be three characters and finally here we need five characters so let's look how we can implement that for now please ignore this warning from the browser google chrome since these form controls are asking for payment details or credit card or debit card details it complains we are not using a secured connection for this page here meaning we are using http instead of https now let's apply those validations here card or a name is required and we have to apply the same validation for rest of these controls also so we have applied required validation for all of these input controls here now inside this card number input control we must have 16 characters so i will set this attribute max length as 16. and also we have to set the mill length as 60 now let me copy paste this for rest of the controls here for the security code we restrict three characters and that of this expiration date we have five characters now we have applied the validation now what we want to show validation error indications for respective controls so first of all if this form as a whole is not valid i will disable this submit button so that we can prevent the user from submitting this form here for that first of all we have to set a local reference for this form here and we can do that like this for so here we have the local reference and we will assign it with this ng 4 now we can refer this form here with this local reference here 4. now with this we can disable this submit button here we will apply this attribute disabled if the form is invalid so that we can check this property invalid so this is how it works this disabled is a property for this button here if we assign this with true here then this button will be disabled and that happens when this form as a whole is invalid now let's check that here because of this disabled property here the submit button is disabled since this form is not valid as a whole now let's populate this form with random values like this 16 digit card number security code expiration date that's it when this form as a whole is valid this button will be enabled now let's show validation error indications to respective input controls here so first therefore we have to familiar with some properties related to validation so head over to the official documentation for ankula which is angular dot io then search for form control here so here it is so all of these form controls inside this form will be treated as a form control in angular within this class we have some properties related to validation first of all these two properties valid and invalid these properties indicates whether a given property is valid or not and then we have these two properties test and untest indicating whether a given control is touched at least once after rendering the form and then just about that we have these two properties pristine and dirty if the control still holds the initial value then this property pristine will be set as true generally validation in angular is done using these three pairs of properties here so let's look how we can do the same inside our app so we will do this we will apply this class invalid i have already added corresponding css rules inside this global style sheet here styles.css so if an input control has this clause invalid respective control border will be set as read so back to the html form here for that you can use the shortcut hold ctrl then press tab so that we can easily open the recent file hold ctrl then press tab so we will apply this class invalid based on the condition that we are going to specify here so here is the condition if this control card or a name is invalid and it is test card on a name dot test back to the application currently this control is invalid still there is no red border because we have not yet touched the control just paste the cursor inside the control then click outside so currently this control is touched and still it is invalid and then this invalid class will be applied we are not using the property pristine or dirty you could use that property also for example instead of test we will check this property dirty meaning there is a change from its initial value still if it is invalid we will apply this invalid clause here so based on your logic of implementing the validation you can make use of these properties here for this form validation we will be using test instead of dirty now let me copy paste the same forest of the controls here now we have to change this control name appropriately so instead of card on a name we have to use card number so select the word ctrl d then paste the card number here now back to the application let's check whether validation is working or not first of all this form as a whole is not valid so this submit button is disabled let's try the validation of this card number here let's try a random card number one two three four five six seven eight nine zero one two three four five still there is only 15 characters so this control is invalid now there is 16 characters so this control is valid now so this is how validation works in ankula this is not enough in a practical application you have to implement the same validation in server side also for that you have to add corresponding attributes for these properties i will leave it for you later you could do that once you complete this tutorial now we are going to submit this form into the asp.net core web api here we are already running this api through this option start without debugging now let's submit the form so that we can insert a new payment detail into the db so first of all i will add submit event to the form here so let's add the submit event like this submit the form submit event will be handled inside this function on submit into that we have to pass this form reference here so 4. now let's define this function inside this typescript file here on submit for this function we have a single parameter form which is of the type ng 4. now within this function we have to make a post request into the web api here for that we will define a separate function inside this service clause here in order to make http request from ankula application we will be using http client so first of all let's import that up here from angular common http we have to import http client now let's inject the same inside this constructor here private http of the type http client now to make the post request i will define a new function post payment detail now inside the function we could do this this dot http dot post function can be called as a first parameter we have to pass the url up to this post web method inside the controller here now let me copy this i will define a read-only property here base url is equal to i will paste the same api forward slash payment detail now we can pass the same here base url as a second parameter we have to pass an object of payment detail which is to be inserted like we have done here within this ui so we have to pass a json like this through this second parameter here it will be the inside this form data properties since we have binded its properties through two-way data binding here so whenever we change values inside these input controls here corresponding properties card owner card number whatever will be updated accordingly so while making this post request we just need to pass the object form data here now when we use this class http client we have to import corresponding module into app.module.ts file here so let's add that into this imports array http client module so this will make a post request into this web api method here and this function returns an observable as you can see here so i will return the same from this function here now back to the component typescript file we can call the function here this dot service dot post payment detail we will call the function here it returns an observable so we can subscribe to that to work with the response subscribe as a first callback function we have the success function so when this request is successful this callback function will be invoked so whatever we have to do when this request is successful we can do that within this pair of curly brace here if there is an error we can handle that inside this second callback function here for now i will just print the error message in console window so we have done everything for making the post request there is one more thing we often forget when we access an api whether it is asp.net core or python django whatever it may be there will be a security feature called course when an application try to consume this web api from an application which is hosted in a different domain or port number it will block that application from accessing its resources it's called course cross resource sharing so first of all we have to allow request from this port number inside this web api here now let's look how to enable course in asp.net core web api we could do that inside this startup.cs file here inside this function configure services we will add course so services dot add course and within this configure function we can allow request from our ancula application for that we can call this function app.use course function can be called in order to work this approach we have to call this function before these routing here now inside this function we will pass this arrow function options from that we can call this with origins function as a first parameter we have to pass the url of this angular application so i will just copy that from here and paste the same here and you must remove this last four slash here now in order to allow all of the web methods like get put delete etc you can call this function hello any method then after that in order to allow all of the header request header configurations we could do this in order to reflect these changes in running instance of this web api let me save this and then build this project again now let's try to submit this form so that we can make the post request into the web api card order name card number security code valid through submit the form hope we made the post request successfully let's inspect this application here there is no error showing let's check our db here let's execute the select query here boom so here we have the card details of ava elliot so this is how we can insert a new record from ankula into asp.net core web api now after submitting a form like this we have to reset its form controls and also we have to show corresponding notification say this operation is been successful so first of all let's reset this form so back to the corresponding component i will define a function here reset form with a single parameter form of the type ng ng4 in order to reset an angular form we can make use of this ng form instance or the reference of the form inside that will be having another property with the same name form from that we can call this function reset and it is also recommended to clear these properties that is used for data binding here from this property form data so i will just assign this property form data with a fresh instance of the payment detail model so i will just update this form data with a fresh instance like this this dot service dot form data is equal to new payment detail now let's call the same inside this success function here reset 4 into this function we have to pass an instance of the form here now in order to show the notification i will be using the npm package ngx toaster so head over to the website npmjs.com then i'm gonna search for the package in gx toaster so here it is so here is the installation command let me copy that from here while installing this package please do check out this dependency section here where you specify the compactable version of angular with its version for versions above angular 10 the current version is suitable for the future versions of angular it might not be the case so always check out this table dependencies and install the corresponding version so i have copied this installation command now back to vs code let's open a new terminal i will paste the copy command here along with this package name make sure to include the version that you can do with this at the rate simple then provide the version that you can copy from here currently i'm installing the latest version based on your ankula version you could copy the version from here let me paste the same here we don't have to do this since we are using the latest version if you want to install a different version from latest version you have to do like this now hit enter so here we have installed the package now back to the package documentation here along with installing this package we also have to install it dependency package and cooler animations by default this package will be already installed inside your application that you could see inside this file package dot json here angular 4 slash animations so we don't have to install that again now we have to update our app.module.ts file we have to add browser animations and this toaster module also first of all let me copy these import statement from here and let's paste that here browser animations let's add that into this imports array and we also have to add toaster module from that we can call this function for root through this function we can pass global options or configurations for this toaster package as mentioned inside this documentation here so these are the options that you can play with configuring this package and you could pass an object with those options like this within this function for root for now we are not going to change any of the default configuration now back to the component here payment detail form component in order to show the notification with the install package first of all we have to inject corresponding service class here so private toaster of the type toaster service click on it it will add the corresponding import statement at the top if not you have to add this impose statement manually to show a notification we could do this this dot toaster dot success function can be called so it will show a green notification message so here is the message submitted successfully as a second parameter we can pass a title for the notification for now i will set it as payment detail register finally we have to do one more thing we have to add the reference for this style sheet from the package toast.css it will be the inside this directory so all of the packages that we installed into this application will be the inside this folder not modules so here is our corresponding package folder ngx toaster inside that we have this style sheet toaster.css now we have to add the corresponding star sheet reference inside this json file angular json so let me copy this reference from here now let's open angular.json file so here it is and then search for styles array actually there will be two styles array one is inside this build object and there will be one more array with the same name stars within this test object we have to add the styles reference into this build object array stars inside the array we already have the default style sheet reference stars.css inside that we have added some predefined css rules now let's paste the toaster style sheet reference here most of the time when we update files outside this src folder we may have to restart the server so let me open the terminal here view terminal and here is the terminal where we have started our server in order to restart this server first of all we have to stop it so use the shortcut ctrl c then type y for yes and execute this command again ng double dash o now let me insert one more record to verify the reset operation and the notification works properly submit the form boom so here we have reset the form and you could see the corresponding notification message here now i'm gonna retrieve all of these records from this table payment details with the help of web api get web method here get payment details so back to the angular application here then open this service clause in order to store list of our payment details i'm gonna add a new array here list which is an array of the type payment detail model clause now let's define a function to retrieve all of those requests from the web api and we will save that into this array here so here is the function refresh list to make a get request with http client we could do this http dot get function can be called and let's pass the base url here and this function also returns an observer so i will just convert that into a promise so just call this function to promise and then here is the success function inside that we have this callback function to deal with the success response here we can do this this dot list we are going to assign the response data that is retrieved from the uh server so you want to convert this response into payment detail array so here we have the function it will make the gear request to retrieve all of your records like we have done with the get request here and then we will save that retrieved request into the list array here now we have to display these list offer requests inside the parent component in place of the second grid column here so here is our parent component payment detail typescript file first of all i will inject the service class here service as payment detail service and we will call this new function refresh list inside this ng on a life cycle hook this function will be invoked when this component is completely rendered so we could do this this dot service dot refresh list so this function will initialize the list that we have inside the service class here now with this array we can design a table to show all of zero codes so here is our parent component html file here we have the bootstrap grid inside the first column we have shown the form for the correct operation and inside the second column we can show a table to list all of your code that we have inserted instead of this pan element here we need a table with this class table from bootstrap and then inside that we have t head with this bootstrap class t head light inside that we have this row with four header columns so th into four inside the first column we will show card honor then card number as you can see the meta abbreviation is really helping me and then we have expiration date so here it is and inside the last column we will be showing action buttons like delete and update just after this t-head we have t body inside this t-body we need double rows as much as the course that we have inside this array so basically here we are going to iterate through the array for showing each of the payment details so we could do this so we will be showing table row by iterating through the array inside each array we need four td cells so here it is in order to i trade through the array we could do this you can use this ng for detective and g4 is equal to let payment detail so pd of service dot list so here we are going to iterate through this list array from the service and on each iteration the corresponding iteration record will be saved into this variable here pd with that we can show the corresponding record details inside these td cells here pd dot card owner name pd card number expiration date and inside this last column we will show an icon for delete operation so here it is i element with these classes for the phone over some icon for then for trash alt then to enlarge this icon we can use this class and to color the icon we have text danger class from bootstrap now let me save this and back to the application here boom so here we have the course that we have just inserted before after making these changes inside our application i was getting this error even though there was no such error inside our application so i decided to restart the server so everything went uh successful so while you develop the application if you are getting errors like this even after you have done everything properly try to restart the application it might resolve the problem i hope angular team will resolve these problems in future now let's look how to update this record here for that user can click on this array the corresponding record details will be populated inside the form here after making required changes inside these controls he can submit the form for the update operation so first of all we have to wire up a function for the click event for this row here so back to the parent component html let's add a click event for these td cells here click is equal to we will call this function populate 4 into that we will pass this object corresponding to the current payment detail now let me copy this and pasting for rest of the td cells except the last one now back to the parent component let's define the function here populate form for this function we have a single parameter selector record which is of the type payment detail model clause now in order to fill the selector record details inside the form here we just need to update this property form data in service clause for that we could do this this dot service form data is equal to selected record now if we directly assign the selected object into this form data there is a problem let's check that here when we click on this array corresponding the code details are populated here now as we change values inside these input controls here at the same time the property will be saved inside this table also it is because of this direct assignment here we are just passing the reference of this object into this so whatever changes we make inside this will also reflect inside this object also so in order to avoid this problem we are going to make a copy of this object and then assign that into this property here so we could do this object dot assign then as a first parameter we can pass this empty object and then we could pass this selected record here now user can make the required changes here and then after that he just need to submit this form here inside the form submit event we have to handle the update operation also so here we have the corresponding component payment detailed form inside the submit event function on submit we have already done the insert operation now we also have to implement update operation also so i'm gonna define separate functions for insert and update operation so insert record with a single parameter form of the type ng form now let's cut this insert operation from here and then i will paste that inside this new function now i will define another function for update operation update record inside this on submit function we will decide whether we have an insert or update operation based on the id value we have already added a corresponding input hidden field here so based on the value of this property payment detail id we can decide whether we have an insert or update operation initially it will be zero we will do the insert operation for an update operation there will be a non-zero value so here we have the if statement inside that we will check the value of the id so this dot service dot form data dot payment detail id if it is equal to zero then we will do the insert operation we can directly call the function insert record by passing this form parameter else we will do the update operation for an update operation we have to call this put web method from our asp.net core web api here so i will just define another function inside this service clause here it is almost similar to this post function so i will just copy this and pasting that below put payment detail instead of post function we can call this put function for an update or put web method we have to pass the id along with the url so we could do this we will be using the string interpolation so we will just enclose this url within backticks here we have to replace the value from this uh read-only property so we can do this and then after that we need a forward slash followed by the id of this object so we could do this this dot form data dot payment detail id inside this function also we have returned the observable from the put function and we will do the rest of the job while calling this function put payment detail that is inside the function here within this payment form component invoking the function is similar to this function call here so i will just copy this and pasting here is called this function put payment detail if the operation is successful we will reset the form and we'll be showing this uh notification torso message as info so that it will show the notification in a blue color and we will say updated successfully let me update this record here before that i want to prevent this auto complete or auto prediction from previously posted data for that we just need to update the form design here just add this attribute autocomplete as off for the form okay now back to the application to update this record click on it then change the details as you wish in order to check whether the update operation is working or not usually i add this suffix with aztec marks submit before so here we have successfully updated the record but it is not shown here because we have not yet refreshed this table here so back to the application and then to the typescript file of this form component we have to call this function this dot service dot refresh list now let's call the same inside the insert function also save back to the application so after saving the project here the application here automatically reloads and thereby here we have the updater data now let's try to update that back to the previous value so let me remove this asterisk marks from here submit the form boom so in this way we will refresh the table after any of the operations now finally here we have the delete operation for that let's wire up a function for this button or icon click event so back to the parent component html file here in order to see all of these opened tabs you could use the same shortcut hold ctrl then keep pressing tab so that you can go through the tabs that you have opened so here is our parent component html let's add a click even for this icon here click now let's call this function on delete into the function we have to pass the corresponding id so payment detail id now let's define this function inside the typescript file here so here we have the function with single parameter id which is of the type number since we are using strict mode here we have to specify the type of the parameter by doing so we can avoid runtime errors while passing data types which we not meant to pass into this function so that's the benefit of enforcing strict mode before completing this function definition here let's define one more function for making the delete request from our service clause so here is the function delete payment detail here we have a single parameter of the type number let me copy this line from here and pasting here instead of calling put method we have to call delete for this function we just need one parameter which is the url for the web method so here we are trying to access the web api method here delete okay so here we have called the function delete with the exact url by appending the base url with the corresponding id so here we just need to pass the id parameter so this delete function also returns an observable so we can return the same from this function now back to the component typescript file here let's call the new function this dot service dot delete payment detail it returns an observable so we can subscribe to that observable here so here we have the success callback and then error callback now let's pass the id into the function when this request fails we will just log the error if the baby i delete the request successfully first of all we will refresh the list from the service so service dot refresh list function can be called and then we have to show the torso notification like we have done inside the form component so first of all we have to inject the toaster service here toaster service this dot toss dot sorry let me rename this properly toaster so toaster dot error function can be called so that it will show the notification in a red color so you can say this deleted successfully as a title we can pass this payment detail register here we forgot to confirm the operation from user side since delete operation involves loss of data we have to confirm that from user side so we could do this we'll just call the function confirm it will open a dialog inside that we can ask this question are you sure to delete this record we will execute this delete operation only when user confirm this operation okay now let's try to delete this record here confirm the operation boo we have deleted the record in web api and the list is refreshed here let's check that inside this management studio here let me execute this select query again that's it so that's it guys here we have implemented asp.net corporate operations with angular using latest versions of these frameworks if you face any problem implementing this application let me know in comment box below you could download this project source code from the github link given below in video description if you found this video helpful please thumbs up this video and for more awesome videos like this please please subscribe to code affection please share this video with your friends and colleagues so that they can also benefit from this have a nice day bye
Info
Channel: CodAffection
Views: 222,668
Rating: 4.9446292 out of 5
Keywords: Asp.Net Core Web API CRUD Operations, How to build Web API with Asp.Net Core, Asp.Net Core Web API CRUD using Angular 11, Angular 11 CRUD with Asp.Net Core 5, Asp.Net Core Web API CRUD with Entity Framework Core and SQL Server, .Net Core 5 EF Core CRUD using Code First, Asp.Net Core Web API tutorial with Angular, Angular 11 with .Net Core Web API, Enable CORS in Asp.Net Core Web App, Insert Update and Delete in .Net Core Web API, CodAffection, Asp.Net CRUD with latest Angular
Id: S5dzfuh3t8U
Channel Id: undefined
Length: 103min 55sec (6235 seconds)
Published: Mon Dec 07 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.