Advanced AJAX CRUD in ASP.NET Core MVC and Dynamic Cascading Selectlist

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello all this is Anis with you welcome to my channel in this tutorial we will see how to create a Ajax scrut application using asp.core MVC let's see the demo of the application which we are going to make this is the create screen of the application in this screen when you select country automatically the cities of the country will be filled in the City Select controlled in case if the country or city is not listed in the select list then you can click the plus button so that a model dialog window will load and you can add the country or city in that model window let's create our first customer enter our present Captain details first first name is Rohit then last name as Sharma and a fake email ID then let's select the country as India notice the cities of the selected country are filled in the City Select control okay let's set the city as Mumbai and browse to select and upload its photo then click the create button to save the customer details perfect our first customer details are stored successfully let's create one more customer this time we fill the details of Virat Kohli select country as India Virat Kohli belongs to Delhi but Delhi is not listed in this city select list so let's press the plus button to load the city creation dialog window in here let's enter city code AS Del and city name as Delhi and notice the countries already set to India and it is read only so that user cannot accidentally change the country here okay let's press the save button perfect the city Delhi is saved and the pop-up window also got closed let's click the City Select list notice the city daily is now added to the City Select list set the city as Delhi and let's press the browse button to select the photo let's select the Virat Kohli photo from the photo folder then let's press the create button to save the customer record perfect the record is saved successfully let's also see the third case this time I am going to create a foreign actor and show you how to create the country using the model dialog window I have filled the details of the Tom Cruise who is a famous actor hope you guys watched the Mission Impossible movie series Tom Cruise belongs to USA But America is not listed in the country select list so let's press the plus button to create the country let's fill the country details and will press the save button to add the country to the backend database notice now the country is listed in the country select list let's select the country as USA and we'll go to the city selection control oh City Select list is empty because we just created the country so let's press the plus button to create the city let's fill the city code and name in the respective text controls and notice the country is already set to the USA and it is also read only okay let's press the save button to add the city wow now the city New York is listed in the select list let's set the City to New York and then we will select and set the profile photo for our customer Tom Cruise after that let's press the save button to save the customer profile perfect the record is saved properly so we saw all the three cases of customer creation that's it with the create screen let's see the other blood operations also this is the detailed screen of the application then let's open a customer profile in the edit screen this is the edit screen of the application let's change the country to USA and notice the cities of the USA are populated in the City Select control let's change the country back to India and change the city to Delhi then we will press the edit button to update the changes back to the database notice the city for Rohit Sharma is changed to Delhi now so the edit module is also working fine in the application then let's change the photo and see whether the photo is getting updated in the edit mode or not then click the edit button yes we are able to change the photo also in the edit mode let's change back the photo to the photo of Rohit Sharma then we will press the edit button to update the photo URL to database great edit action is also working fine in this Ajax scrut application then we will check the delete action so let's load a customer in the delete mode this is the delete screen of the application in the top it displays the confirmation message in case if the user changes the mind they can click the back button to go back to the listing screen but I want to press the delete button to test the delete action so let's press the delete button perfect the delete action is also working fine in the application so all the thread operations are working in the application without any errors this will be a very useful tutorial for you guys so please watch the full video without skipping any part apart from this customer thread we also have two more credit modules in this application namely cut tree and City let's have a quick look at these spreads this is the listing screen of the country module and this is the detailed screen of the country module then this is the edit screen of the country module and finally this is the delete screen of the country module likewise we have the city module but that is very similar to the country module so let's Skip and jump into the development session of the application Ajax stands for asynchronous JavaScript and XML a singer is called means the function call will not block the calling thread and will create a new thread this new thread will work independently and report back to the calling thread after it completes the work due to this the main thread will be in a responsive mode and in a ready state to do any other work this phenomena is very common in Windows forms programming but in web this can be achieved only with the help of Ajax in simple English asynchronous operation is just like going to a tea shop and order for a tea and you can do something else till the tea comes so you are free in the waiting time and you don't need to worry about how the tea is made but synchronous operation is like making a tea and drinking it you must stand near the tea and watch it carefully till it is prepared and then you can enjoy the tea here you are occupied till the tea is prepared and you need to take care of everything like how much tea does to put how much milk to add and how much sugar to add am I confusing you no worries you are going to understand what is Ajax after you complete watching this video okay let's come back to the Ajax Ajax was first introduced in the Year 2005 using Ajax you can read and send data from and to a web server in the background then you can do the partial refresh of the webpage and you can also make the webpage act like a Windows forms application Ajax is a technical term and it is not a language or platform Ajax concept Works using the XML HTTP request object in 2002 JavaScript added a API called as XML HTTP request this XML HTTP request is a standard JavaScript object that allows you to make HTTP requests from the browser in JavaScript it was named at a time when XML was the only open standard language to transfer data in cross-platform domains and between different languages in the sense we be c-shop PHP Java python whatever the language you use understands the XML very well so you can say XML was on its top during the late 90s and early 2000s but later Jason was introduced and after 2010 slowly Jason started to take over the place of the XML and today XML is almost dead or rarely used what is Json Json means JavaScript object notation JavaScript object notation is a standard text-based format for representing structured data based on JavaScript object syntax it is commonly used for transmitting data in web applications Json is used everywhere because it works natively with JavaScript and today almost all the browsers understands JavaScript very well so Ajax music Json is a very powerful and must learn technology Ajax can be used with any type of data including XML Prime text HTML and Json the beauty of Ajax is you can make multiple requests at the same time without refreshing the whole page internally Ajax uses the XML HTTP request object of JavaScript but using this object is not handy and you need to write a lot of code carefully so instead we can use the wrapper methods provided by the jQuery there are two widely used methods for Ajax in the jQuery first one is jquery.getjson and the second one is jquery.ajux but these methods also uses the XML HTTP request object of JavaScript internally we don't want to go deep into that so let's start the coding start Visual Studio 2022 then click create new project after that from the left side suggestion box select asp.net core web app using the model view controller pattern then click next save the project in the C drive slash Advanced Ajax folder give the name of the project as advanced Ajax then click the check box with the description as Place solution and project in the same directory and press the next button then in here leave the framework selection combo box to dot net 6.0 which is the in the long term support then press the create button and wait for the project to get scaffolded expand the models folder then right click and click the add menu after that select new item menu and in here select class as the item type then give the file name as country.cs after that open the country.cs file from the models folder then open the source code folder in the Windows Explorer and then open the one dot text file from there and copy all code from the one dot text file and paste it to the country.cs file after pasting we can see lot of error indicators under the property attributes this is because we have not referenced the required namespaces so to fix these errors open the 4. text file and copy all code to the clipboard and then open the program.cs file and paste the code from the clipboard to the header section of the program.cs file after that we get a different error it says non-nullable property must contain a non-nullable values This Is The New Normal of the dotnet 6 requirement to fix this issue open the project properties window scroll down to find the nullable option and here change the nullable option to disabled and close the properties window and now notice the errors are disappeared next let's create the city model right click the models folder and select add followed by the new item menu then choose the item type as class and give the name of the class as city.cs after that go to the source code folder and open the two dot text file then copy all code from the two dot text file and paste it to the city model kindly have a quick notice on this model the ID code and name property or the normal ones but the country ID property is the foreign key from the country table notice the virtual property of type country when you are having a foreign key property in the model then you must add the virtual property of parent entity type in the child model next step is to create the DB context before creating the DB context file we must install the Entity framework core and Entity framework core tools so select the tools menu and then select nuget package manager and then click the manage nuget packages for solution in here click the browse Tab and in the search box type EF code for SQL server and press enter to start the search then from the search results select the first item Microsoft dot Entity framework core dot SQL Server then select the advanced Ajax checkbox from the right hand side and after that click the install button to start the installation during the installation if you are prompted with the preview changes dialog box then press ok to continue the installation after that press the I accept from the license acceptance dialog box and continue the installation perfect now the EF core installation is completed next we need to install the EF core tools packages this time type EF code tools in the search box then as usual select the first item from the search result Microsoft dot Entity framework code.tools and select the advanced Ajax checkbox and press the install button then press the OK in the preview changes dialog box and I accept from the license acceptance dialog box and continue the installation ok now the EF code tools also got installed successfully next we need to create the DB contacts file right click the solution Explorer and click add new folder and name the folder as data then right click the data folder and click add new item and select class as the item type and give the name as the appdbcontacts.cs after that open the three dot text file from the source code folder and copy all the code from the three dot text file and paste it to the appdbcontacts.cs file then open the app settings.json file in here we need to add the connection string of our database so open the file.txt file from the source code folder copy all code to the clipboard again then come back to the app settings.json file and paste the code from the clipboard after deleting all the existing content from the app settings.json file then after open the 6 dot text file and copy the code from it to the clipboard and then open the program.cs file and paste the code from the clipboard to the program.cs as shown in the video then after go to the nuget package manager console and type add Dash migration space create DB and press the enter key to execute the command now the migration file is created successfully then type update Dash database to update the changes back to the database okay update database command also executed successfully let's verify it by going to the SQL Server open the SQL Server management studio and refresh the databases in case if you don't have the SQL Server management Studio please download and install it it is a free tool from Microsoft notice the database named Ajax example exists this was created by our project let's expand the tables collection yes we have three tables here first one is migration table which is a EF Code table and EF code will maintain all the migration changes in this table then the second table is City stable this is the important table because it has the foreign key column in it then the third table is the country table this this is the parent table for the cities then expand The Columns of the city table in this the country ID column is the foreign key okay all is well so far so good let's go back to the visual studio then right click the controls folder and select add controller and then select MVC controller empty and press add give the name for the controller file as countrycontroller.cs then press add to scaffold the empty controller and then go to the source code folder and open the 7 dot text file copy all the code from the 7 dot text file to the clipboard then open the country controller and paste the code from the clipboard to here then let's try building the application okay it has built it without any errors then we will create The View files for the country controller right click the index action method and then click the add view then select razor View and click add in here select list in the action template method and then select country as the model class then select app DB context as the data context class then press add to start the scaffolding task sometimes Visual Studio scaffolding tasks throws error in the first time while you are trying to create a view file no worries just press OK click add to try creating the view file again wow this time it has created the index.cs HTML for the index action method of the country controller successfully in the same way we will create the view file for the create action method right click on the create action method and click add View then select razor View and click add button then here select the action template as create and the model classes country and select the data context class as appdb context after that press the add button to start the scaffolding task and wait for the task to complete in the same way create View files for the other action methods like data's delete and edit I have done those in the 32x speed okay now we have created The View files for all the action methods of the country controller and next we need to create the menu link for the country controller in the layouts.cshtml so open the layout.cshtml from the shared folder which is inside the views folder in here copy the menu link of home and paste it below then in the pasted menu change the ASP Dash controller to Country and menu text also to Country then build and run the application perfect our application is running let's create few countries India USA and UAE okay the create action is working fine then we will also check all the other credit operations of the country module like edit date tiles and delete perfect all the credit operations are working fine in the same way let's create the city controller so right click the controllers folder and select add controller and then select MVC controller empty and press add then give the name for the controller file as citycontroller.cs then press add button to scaffold the empty controller then after go to the source code folder and open the 8 dot text file from here copy all code from the 8 dot text file to the clipboard then open the city controller and paste the code from the clipboard to there okay let's try building the application it has built up without any errors then we will create The View files for the CT controller first create the view file for the index section by the way we will do all the views creation steps in the 32x speed because we have already seen the steps at the time of doing the country module nothing new here almost same steps instead of country we are going to select City in the model selection box okay the view file index.cs HTML for the index action method is successfully created in the same way we will create the view file for the create action method all these steps are same like country modules create action but select the model class as City instead of country and then press the add button to start this scaffolding task and wait for the task to complete after that open the create.cs HTML which we just created in here change the asp- items to view back dot countries for the country ID select list control after that we need to create the menu link for the city controller in the layouts.cshtml so open the layouts.cs HTML from the shared folder which is inside the views folder in here copy the menu link of country and paste it below then in the paste and menu change the ASP Dash controller to city and menu text also to City okay let's build and run the application now click the City menu and then click the create new link first check is the country select boxes showing the available countries or not yes it's showing so let's create a setting enter boms code and Mumbai as name and select the country as India and then click the create button wow the city Mumbai is created successfully let's create one more City this time we will create Bangalore now let's create The View files for the edit action method then change the ASP Dash items to Wayback dot countries for the country ID select list control let's check the edit action so build and run the application from here select a city to edit perfect the edit screen is showing the country of the city in the country select list okay let's change the city name to capital letters and press the edit button perfect the edit action is working fine then let's create The View files for details method then in the same way let's create The View files for the delete method also okay all the current operations of the city module are created now let's check all the credit operations of the city module since we have already tested the create and edit methods we will check the details and delete method now let's try to delete the city yes the city got deleted so so far so good now all the credit operations are working fine for both the city and the country module actually we have some issues in this project I will tell what exactly it is and how to fix those and also how to avoid them in the real time projects first notice the city New York is present in the cities list now I am trying to delete the country USA let's see what happens actually it's supposed to throw the error but instead it has deleted the city New York and the country USA this is a dangerous behavior and we should not allow this in the real time first we need to understand why this happened this is because by default the EF core creates the undelete Cascade relation for the child tables it means that dependent rows in the child table will also get deleted on deleting the main record of the parent table we need to change this Behavior so to do that we must change the relation type to referential action dot restrict before applying the migration but now we cannot do this because the migrations are already applied so we will handle the situation in a tricky way we will create a empty migration named remove online Cascade then after open the migration file which we just created and notice both the methods named up and down are empty now open the 16 dot text file from the source code folder and then copy and paste the code from the 16 dot text file to the up method actually in this code we are requesting the EF core to remove the existing foreign key which as online Cascade constraint and then add the new foreign key which is of type referential action dot restrict so that the parent row cannot be deleted in the country table when the child rows exists for that country in the cities table then after copy the code from the 17. text file to the down method of the empty migration file and then go to the package manager console and type the update Dash database command and press enter to apply the migration to the backend database wow the command got executed successfully now run the application and try deleting any country which as it is in it see this time we are getting errors this is the correct Behavior but we should not live like this we should handle this error so let's add a try block to handle this error after that in the exceptional handing block catch the inner exception and pass it to the model error to do this open the 18. text file from the source code folder and replace the delete method with the 18. text file code the real time we should not pass the actual error information to the user instead we can pass a custom error message to the user and we should record the actual error message in the log files or in the application event that I will show later in some other tutorial as it is out of the scope for this tutorial let's try to delete the country notice now the country is not deleted but the error message is not shown why okay I found the issue I forgot to add the validation summary spanned to the delete.cs HTML so let's add and run the application again yes now the error message is displayed but the fields of the country are empty why this happens this is because if core first delete the country from its list and then try to delete the country from the database on deleting the country from the database it got error but the selected country is already deleted in the EF course country list so to fix this issue we need to reload the country from the database to do this open the 19 dot text from the source code folder and paste the code to the delete methods exception handling block and run the application again after that let's try to delete the country again this time we are getting the country details along with the error message in the delete screen on error now we are done with the country and city model next we will create the customer model so let's go to the models folder and create a model named customer after that open the 20. text file from the source code folder and copy all code from the 20. text file then come back to the customer model and paste all code from the 20. text file and then go to the app DB context and add the customer table to the DB set properties after that go to the nuget package manager console and type add Dash migrations space add customer table and press enter now the migration file is created we need to do an important step in this migration file so open the last migration file having name ending with as ADD customer table then change the relationship referential action type to referential action dot restrict then after go to the package manager console and type update Dash database then press enter this is a very important step otherwise the EF core will create an undelete Cascade relationship which is not a good practice because in on delete Cascade relationship when deleting the city the customers belong to that City will also get deleted but now the city cannot be deleted when it has dependent rows in the customer table this is the more recommended way to create parent and child relationship okay now let's create the customer controller go to the controls folder and create a controller named customer controller after that open the 21 dot text file and copy all code from the 21.txt file and paste it to the customer controller and next we need to create The View files for the customer controller let's first create the view file for the index action method right click the index action method and click add view then select razor View and then select template as list and then model as customer after that click the add button and wait for the scaffolding task to complete creating the view file next open the layout.cs HTML from the shared folder which is inside the views folder and in here copy the menu item of the city and paste it below then in the paste menu link change the ASP Dash controller to customer and the menu text to customers now let's build and run the application then click the customers menu yes the listing screen is loaded so far so good next let's do the create action so close the application and go back to the visual studio and open the customer controller right click the create action method and click add view then select razor View and click add button and then select template as create and model as customer after that click the add button wait for the scaffolding task to complete creating the view file then open the create.cs HTML file notice it has not created any input control for the Country property because we have made the Country property as a not mapped property in the country model so let's create the input control for the Country property by ourselves copy the input control of city property and paste it above now change the city ID to Country ID in the label and in this select list after that change the ASP Dash items of the country select list to view back dot countries then save and run the application let's click the customer menu and click the create Action Link yes the create screen is loaded and the country's select list box is also filled properly but the City Select list box is empty and even on changing the country's electrics box nothing happens this is because we have not written any code to fill the city list box so far so stop the application and go back to the visual Studio Design time and open the customer controller file now open the text file named 22 from the source code folder and copy and paste the code from the 22.txt file to the customer controller this code will add an action method named get cities by country this method has the written type as Json result actually we can have action result also as written type but when you are returning the Json string it is recommended to have the Json result as the return type in here we are passing the country ID as a parameter to fetch the cities belongs to that particular country after that we fill the list named cities by selecting the ID and the name of a cities matching the country ID and finally we pass the list to adjacent result object and returns to The View so we are done with the controller let's go to the view file open the create.cshtml from the customer folder which is in the views folder here we have to write a JavaScript function to make the Ajax cards to fill the cities of the selected country so open the 23.txt file from the source code folder then copy and paste the codes of the 23.txt file to the script section of the create.cs HTML this script is very important so please listen carefully first of all I made the filling of City dynamically using the Ajax as a function so that it is a portable and you can copy and paste it to any of your project this function has two parameters the first parameter is a select list control you need to pass the select list which has the country details then second parameter is the ID of the City Select list control then I am using the jQuery method to get the reference to the City Select list by the ID next I am deleting all the options from the city select list after that I am adding the default option as select City after that I am finding the currently selected country ID then if the country ID is found successfully we are making an Ajax request to customer controllers get cities by Country Action method using the get Json method of the jQuery please note I am also passing the selected country ID to the parameter country ID of the gate cities by country method after that on success I am creating a callback function to fill the cities to the City Select list in the Callback function I am checking is the Json result is received if received then I am filling the City Select list after that we must call The Fill cities function in the on change event of the country select list here we are passing the first parameter as this and it means we are passing the country selectors control reference and the second parameter is the ID of the City Select list please note I have added the ID attribute to the City Select list okay that's it we are done let's run the application and create the customer now the customer screen is loaded successfully let's select the country and notice all the cities belong to that country is filled in the City Select box oh I forgot to add the file input control but Ajax is working fine so let's add the image and file input control to our customer creation screen so that we can save the customer profile photo also open the create.cs HTML and first delete the input control for the photo URL and then open the 24. text file from the source code folder and copy and paste code from the 24. text file to the create.cshtml after the submit button notice I have kept the photo URL in the hidden div this is because I don't want the user to enter the photo URL instead we will take it from the file upload control next open the 25. text file and paste it above the submit button after that open the 26.txt file and copy the code from it and paste it to the top of the create.cs HTML I mean just below the view data of the code as shown in the video then copy the image named no image.png file from the source code folder and paste it to the images folder which is inside the www root folder if there is no images folder in the WWE root folder then create a folder named images inside the www.root folder after that open the 27.txt file from the source code folder and copy the code from it and paste it in the script section below the fill cities method and next open the 28.txt file and copy the code and paste it to the form tag this we do because when uploading file to the web server the form encoding type should be multipot slash form data after that open the customercontroller.cs file then open the 29.txt file and copy the first line and paste it to the customer controller below the read-only variable app DB context then after copy the second line from the 29. text file and add it to the parameter section of the Constructor method and then copy the third line from the 29.txt file and paste it to the Constructor method after that open 30. text file and copy the get profile photo file name and paste it to the customercontrol.cs file next open the 31.txt file from the source code folder and copy all code from it to the clipboard and then scroll up to locate the HTTP post create method in here inside the copied code above the line which says contact dot add of customer then build and run the application now let's try creating our first customer perfect the cities are getting filled on changing the country so our Ajax code is working fine let's add the photo or customer Virat Kohli then we will say our first customer profile wow it got saved so we are done with the create module let's do the edit module now before doing the edit module we need to do something important module is also going to be same as the create module only with slight difference since we are going to use the same JavaScript functions in the edit module first we need to move the JavaScript functions to the site.js file so let's move it okay now we have moved the JavaScript function to the site.js let's build and run the application oh no the age of stopped working see I am changing the country but the cities are not failed why I guess there is some issue in the site.js file let's go to the site.js file to find and fix the issue yes I found the issue the at url.action is the server site code we must not keep any server set codes in the site.js file because site.js file is a client-side script file so remove it and just change the line to get Json of customer slash get cities by country within codes as shown in the screen okay let's build and run the application again wow now the Ajax methods are working fine see when I change the country the cities belongs to that country are populated in the City Select box okay that's it with the create module let's create the edit module go to the solution Explorer and expand the views folder then expand the customer folder in here copy the create.cs HTML and paste it there after that rename the copy of the create.cs HTML to edit.cs HTML then open the edit.cs HTML and change the asp-action to edit in the form tag then open the 32.txt file and copy the code and paste it above the model summary error div basically we are creating the hidden input type control for the ID property of the customer model then scroll down and change the value attribute of the submit button to edit next change the source attribute of the preview photo image tag to Images slash model dot photo URL this code is available in the 33 dot text file you can copy and paste it from there after that let's save and run the application then load any customer profile in the edit module now the customer profile is loaded in the edit module but notice the country and city is not loaded but no worries we will fix the issues first we need to change the edit method to fetch the customer with the cities so go to the customer controller and locate the edit method then open the 34.txt file from the source code folder and copy and paste the code from there after that notice I set the customer dot country ID equals to customer dot City dot country ID this I am doing because country ID is an unmapped property and it will be null by default so we need to do this manually and next we need to include a private function named get cities which will return a list item instead of Json so open 35 dot text file from the source code folder and copy and paste the get cities method from there and next go to the edit method and set the viewback dot cities equals to get cities of customer dot country ID this code is available in the 36 dot text file and then go to the edit.cshtml and set asp- items of the City Select list to view back dot cities that's it let's build and run the application now load a customer in the edit mode wow the customer is loaded correctly let's change country see the cities of the selected country is populated properly so the edit module is also working fine now let's do some modification in the customer let's change the email ID and save the customer oh no we get error saying please select the customer profile photo but this error is no way related to the Ajax it is okay we will fix this error also but Ajax is working fine now open the edit.cshtml and in the input control for photo URL remove the value attribute which says value equals to zero link string after that open the 37.txt file from the source code folder then copy and paste the code to the edit method of the customer controller above the line which is attaching the customer object to the EF core context basically we are checking is the user uploaded new photo if so we replace the old one with the new one otherwise we preserve the old photo with the customer record and then build and run the application then try editing the customer data yes this time the record got saved successfully then let us also try to change the photo yes the customer photo is also changed successfully so our edit action method is also working fine next let's do the details and delete action go to the solution Explorer explore the views folder and select the customer folder copy the edit.cs HTML and paste it there after that change the name of the pasted file to details.cs HTML then open the details.cshtml and first change the heading to details after that remove the style tag we don't need it here then remove the form tag also and all the validation span elements accept the validation summary span and then remove both the select list I mean the country select list and the City Select list then after add the normal input control for the country and city property then change the ASP dash for tag helper to model.city.country dot name for the country input control likewise change the ASP dash for tackle part 2 model dot City dot name for the city input control after that delete the file upload input control we don't need the file upload input control in the details section because details Pages always read only and remove the submit button also in the place of the submit button add a attack the code for the attack is available in the 38 dot text file in the source code folder next make all the input controls as read-only since this is a Details page and we are not going to submit anything back to the database so it's better to keep it as a read-only then add the bootstrap class form Dash control dash line text to all the input controls which are read only after that open the customercontroller.cs file from the controllers folder and then change the details method fetch command to include the city and Country entity along with the customer entity to do that open the 39.txt file and copy all code and paste it to the details method of the customer controller then build and run the application now select a record in the details mode perfect all the details of the customer are shown properly notice the city name and country name are also shown properly next in the same way we will do the delete action method delete action method is very simple go to the solution Explorer explore the views folder and select the customer current folder copy the details.cshtml and paste it there after that change the name of the pasted file to delete.cs HTML then open the delete.cs HTML and first change the heading to delete for delete we need a form tag and submit button so add the form tag and set the action of the firm tag to delete okay that's it let's build and run the application now let's open the customer Virat Kohli in the delete screen but I don't want to delete Virat Kohli he is a nice person and good batsman so let him in the be in the team we will click the back to list link with this the customer module is completed but don't go away I will show how to bring the model dialogue using Ajax which we saw in the demo so please stay on first we need to install a client-side library called jQuery dot unobtrusive Dash Ajax to install this library right click the solution Explorer then select the add menu and then click the add client site Library here you will get a model window named add client-side Library in this leave the provider as CD and Js and in the library text box type Ajax then from the suggestion box select the jQuery dot unuptrusive Ajax dot Min dot Js the latest version is 3.2.6 now click install after that the library will be added to the ellipse folder of the www root folder let's explore this folder and we will make sure that library is added properly to here this Library will add additional features to the Ajax capabilities let's see what it is export the views folder and then explore the shared folder inside it right click the shared folder and click add and click view then select Reserve you empty and give the name as underscore create model dialog.cshtml of the recording I have created the HTML mockups for the dialog window please copy the htmls of the dialog window actually this HTML is very easy to understand first create a div with ID as do create dialog holder this div will be the parent div and it has the class as model fade this class is very important so please have extra attention after that add the role as dialog this is also important so that it stands out as the model window okay let's come to the next div this is the dialogue window so put class as model Dash dialog and next create one more div this is the content div so give class as model Dash content then inside it add one more div and give the class as model Dash header then inside this add H to tag and put heading as create and then add a button and give the class as close and set data Dash dismiss equals to model this is very important so that when you click this button the model dialog will hide and will get closed after that add one more div named due create dialogue and set the class as model Dash body this div is very important and notice the spelling of the ID this ID we will be using soon so please make sure you note it down properly after that add one more div and set the class to model Dash footer inside this div add a button and set the class to button Dash Danger then set the data Dash icon to close and then set the data Dash dismiss to model okay that's it we are done with the model dialog please have a look at the complete code and copy it properly if you really want to bring a pop-up window type entry screen after that go to the solution Explorer and select www root folder then expand the www root folder and select the JS folder and expand it then from here open the site.js file and scroll to the bottom of the file and in here add a JavaScript function named show create model form and inside it called the jQuery method model of show for the div named div create dialog holder and next go to the country controller and add a action method named create model form then inside it add a variable named country of type country and set it to a new instance of country then return partial View and in the first parameter pass the partial view name I mean create model form then in the second parameter pass the country model after that go to the solution Explorer and open the validation Scripts partial.cshtml in here add the link reference to the jQuery dot unobtrusive ajax.js file after that open the layouts.cshtml and in here add the partial view underscore create model dialog before the render body then after expand the customer folder from the views folder and open the create.cs HTML file from the customer folder and near the country select box add a div and place a button inside this div on clicking this button we are going to call Ajax function named show country create model then wrap the select country div and the show country create model div inside a button Dash group div as shown in the video okay let's write this Ajax JavaScript function so go to the script section and write the function sorry I forgot to tell you add the ID for Country select list this is a very important step and then let's go to the script section this time we are going to use the Ajax method of the jQuery last time we have used the get Json method of the jQuery but not a big difference between that and this this method has three parameters first one is URL in the URL type slash country slash create model form remember we created this method in the country controller then the second parameter is called type so put call type as get then the third parameter is on success here we need to write a callback function which will get fired on success of the call in this callback method we are going to fill the due create dialog due with the response we received from the controller method after that we are showing the model create form of the country so we are almost done now go to the country controller file and right click the action method named create model form then click add View and then select Reserve you then include a underscore before the view name I mean change the view name to underscore create model form this is because the partial view name should always start with an underscore then select the action template as create and set model class as country then select the data context class as appdb context then press the add button and wait for the scaffolding task to create the view file for us excellent The View file creation is completed now let's build and run the application to check the output of what have we done so far wow notice the green button near the country select box let's fill the customer details and press that button great we got the model dialog window now but still our job is not complete so please wait and watch till the end if you try to create a country using this model dialogue it will not save because we have not written the post method yet so open the createmodelform.cshtml from the country folder in here first remove the underscore from the form's target action attribute after that open the countrycontroller.cs file then in here add a action method of type HTTP post and name the method as create model form the important thing to notice here is the return type of this method the return type is no content it means this method will not return any view file to the color function because this method is going to be called by a Ajax model form okay let's build and run the application to check the output now let's create a country enter code AS Chi and name as China and the currency as n then press the create button we click the create button but nothing happens the model dialogue supposed to get closed right that's what we saw in the demo no problem let's close the dialog manually and check the country list yes the country is created but this is not the way it should work no issues let's see what went wrong first stop the application then open the country controller and scroll to the bottom of the file after that write an action method named get countries this method will fetch all the country names and Country IDs from the database and will pack it inside a Json result and will pass the Json result to the caller function then after open the partial view file named create model dialog dot CS HTML from the shared folder which is inside the views folder in here comment the close button do this is a very tricky solution I don't know whether you guys can understand or not but as a teacher it is my responsibility to make you understand so don't worry actually it's not rocket science I have created a fake footer bar this footer has two buttons with IDs these IDs are going to play very important roles so please note down the IDS of the buttons the first button with the ID as do back button is going to do the closing of the model window this is the replacement button for the one which is boxed in the red the second button with the ID as dupe submit button is the very very important one this is going to do the submission of the model window form next notice the JavaScript function named as submit model form this is the function actually does the form submission okay that's it with the model window then open the site.js file from the www root folder in here scroll down to the bottom of the file after that add the function named submit model form this function such as for the button with the ID as button submit and Rises The Click event of that button very nice isn't it water technology now we need to open the create model form from the country folder which is inside the views folder then give the ID as BTN submit for the submit button then make the parent div of the submit button to Invisible by setting the display style attribute to none then comes the important steps in the form tag of the country create model form add the Ajax attributes notice we have set data Dash Ajax to True by setting this attribute to true we are informing the Ajax library to do a Ajax submit instead of the normal submit then we have set data Dash Ajax success to refresh country list that means if the post succeeds then on return the JavaScript method named refresh country list will be called so let's write this method in the site.js file open the site.js file and scroll to the bottom of the file this method is very interesting and important one first it gets the reference to the do back button then Rises The Click event of that button so that the model dialog closes and the focus goes back to the country select list after that we call the Ajax function named field countries to fill the country select list to add the new country which we just added and then we need to write this Ajax method named field countries so please copy down the method this is very similar to the gate cities by country method okay let's build and run the application then let's click the customer bedroom and then click the create new link after that let's fill the customer details and notice the country select list does not have the country named USA in the list okay let's fill the country details and press the save button perfect this time the model dialog box got closed on clicking the save button let's check the country select list yes the country USA is added to the select list so our country model dialogue is working fine next we will do the city model dialogue City model dialog is slightly different because we need to pass the country ID to the gate cities by country method so it is going to be little challenging actually I thought of keeping it for the part two but this time no part 2 I will complete the city dialogue also now go to the solution Explorer and open the citycontroller.cs file and then scroll down to the bottom of the file after that add two methods named create model form the first method is of type HTTP get and second is of type HTTP post these methods are very similar to the one which we did in the country controller notice the error indicator under the variable country name this error comes because presently our city model does not have this property so open the CT model and add the country name property and make this property of type string then add the not mapped attribute to the head of this property after that add the max length attribute and set it to 75 then come back to this citycontroller.cs file in here add a method named kit country name the purpose of this method is to get the name of the country from the database by passing the country ID as the parameter then right click on the create model form method name and click add View then here change the name of the view name to underscore create model form this is important because it is best practice to start the partial views name with an underscore after that set the template select box to create then set the model class to City and then make sure you selected the create test partial View checkbox after that click the add button wait for the scaffolding task to get complete after that open the partial view file which we just folded in here remove the underscore from the forms asp-action tag helper then open the underscore create model form dot CS HTML file from the country folder and copy the forms Ajax attributes to the clipboard then come back to the cities create model form dot CS HTML file and in here paste the Ajax attributes to the form set from the clipboard then change the method refresh country list to refresh City list because this time the City Select list needs to be populated to that make the parent div of the submit button to Invisible then delete the back to list div then after open the createmodelform.cshtml from the country folder and delete the back to list from here also actually I forgot to delete during the country module development then copy the jquery.validate dot unuptrusive.jscript file very important point to notice here this Library needs to be added to the bottom of your partial view file otherwise the client-side validations will not work on partial views it is a bug then open the createmodelform.cshtml file from the city folder and paste it there next open this site.js file then scroll to locate the function named refresh country list and below that add a function named refresh City list this function is very similar to the refresh country list but here we find the country select list using the document.getelement by ID and passing it to the field settings function and next scroll to the top of the site.js file to locate the show country create model function and below that add the function named show City create model this method is very similar to the show country create model then open the create.cs HTML from the customer folder scroll to locate the City Select control and then add the plus button div below the div of the City Select control then add a parent div to hold both the city selective and the plus button due after that change the style class of the City Select control due to call Dash 11. then close the parent div now notice the on click event of the plus button of Select City control this button will call the JavaScript function named show City create model to show the pop-up model form next open the create model form from the city folder and delete the select list of country ID after that add a hidden input control for the country ID property and a read-only input control for the country name property the hidden property is the foreign key property and it is a mandatory field here then this country name property is the not mapped property we will populate it manually in the create model form action method of the CT controller then give the ID for the submit button this is also a very important step so set IDs button submit be careful with the spelling it is case sensitive okay that's it let's build and run the application let's select the country as USA and notice there are no cities showing in the City Select currently let's click the city plus button to load the model dialog in here let's enter city code AS NY and city name as New York and countries already showing as United States of America click the save button to add the city to the database wow the model dialog is hided after saving the city let's click the City Select list notice the city in New York is listed in the City Select list excellent right then select the photo of Tom Cruise and click the create button to save wow the record is saved hope you enjoyed the tutorial with this I am completing this video before I sign off I request you to subscribe and share this video I would appreciate if you would like and subscribe to this channel so that you will be notified for all of the new videos that I will be posting thank you and bye for now
Info
Channel: CodeS
Views: 19,575
Rating: undefined out of 5
Keywords:
Id: apVQMsHjT6w
Channel Id: undefined
Length: 90min 3sec (5403 seconds)
Published: Mon Oct 24 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.