How to create dynamic Charts in ASP.NET MVC

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys welcome to digital tech join so in this video i'm going to show you how to create charts dynamically from fetching the data from database and creating various different types of charts like bar chart line chart and uh pie chart so i'm going to use asp.net mvc and visual studio 2022.net framework 6.0 so for the charts i'm using chart.js which is an open source html based javascript charts i want to show how to create install and you know configure your charts in your asp.net application and this is i'm doing dynamically so this data is getting load from the database which is ms sql server so let's get started i'll also show you before i go deep dive into this practical session i've created a bar chart and then i've created a line chart then a pie chart and a donate chart there are various other types of charts available in chart.js but this video helps you to get started with creating basic charts and then you can explore and deep drive to create more advanced uh charts in your asp.net so let's get started so we are going to use our visual studio 2022 for this project and i'm using a database sql server 2008 you can use the latest version also i've created a database called the graph demo and i've created a table called sales data and i'll just show you the design it's a basic design where i have an id then a month name and total sale so this is the data which i have created and inside the date table i have added the following sales data for six months i want to present this in in the charts and i'm going to use the chart.js as i mentioned earlier so let's get started i open visual studio 2022 and i select asp.net core mvc framework click on next and sales data this is a project and this is a default path you can select your own path and this is the solution name sales data chart and click on next and take configure for https as of now i'm using framework 6.0 and click on create so our project is loaded so we have a default structure provided by dotnet will not get into this details but let's go ahead and first create a database connection to fetch the data from the database so for that let's go to our app setting and quickly add the connection string to our database next string let's name it as default connection and server it's local database is databases graph demo and i'm using integrated securities through if i set as integration integrator security is false then i have to provide the username password of this local instance database which you can do it so created the connection string and now let's go ahead and add our model class so click the model folder right click and you say add class name as sales entity and using this system dot component model dot data annotation and then define the key so we have prop tap enter and id and then string name of the field is month name and then drop tap tap enter and total sales total sales so this is a field and this will be our index okay so a model is ready before we start getting into connectivity of database let's go ahead and add the required packages right click on the project manage nuget browse select type core so you have to select this entity framework 6.0.5 click on install click ok accept so it got installed then you have to select database so it's skill it's sql server so you get this one since we are using mxsql server database we are using this library entity framework sql server click on next install ok and i accept also use the razer runtime so i'll explain what is this for so you select this one microsoft asp.net core mvc razer runtime compilation this is required when you make any changes in your html and you want to just refresh and look at the changes without rebuilding the application so this we might required because we want to refresh as and when the changes are reflecting so we add this so we have now added the following libraries one two and three libraries so let's go ahead and set up the database connectivity so since you added the runtime library just go over here and enable that razer enter say builder dot services dot add razer pages so we have added this so we'll be able to refresh it i'll just increase the font size so that it is visible to everybody click on font and it's 15 and make it to 16 okay now let's go ahead and set up the database connectivity for that let's create a folder called data layer right click on that add a class called db contest sales so this is a db contest class make sure you add the microsoft dot entity framework core also you add the reference to our model class now this class will inherited db contest and just click on this db contest sales this option comes in and you select generate constructor for sales so all this i've explained in my previous chapter so you can go and refer the videos and paste those in the links about the database connectivity and how you have to connect so i'm just proceeding fast so that i come to the main subject of creating charts in asp.net now here you create a db set and you will refer to your entity class and provide the table name so your table name is sales data so this is sales data so this is done now let's inject this connection string in our program dot files here select using microsoft entity code using refer your sales data chart dot detail here and using sales data dot models and then just after the compilation you say builders dot services dot add db contest and you maybe select your db con db contest sales which you created options lambda expression enter options dot use sql server because we use sql server and then builder dot configuration dot get connection string and you default connection this is the name of the string that you have so we added the connection so we have set up the database entity and the database connectivity now now let's go ahead and add the controller so we have a default controller but for learning purpose and our particularity we are going to add a new controller let's select an empty controller and name it as sales records okay sales records or sales record so this becomes a controller now in this controller we have a default action index now let's create a new action item called show sales data this will just return a view let's go ahead and add this view into our select a razor view empty so what is the name it's sales show sales data so now you can notice that view as a sales record which is a controller name and then it has a sales view now let's go ahead and now explore our framework called chat so what is basically i'm using this framework which is very known well-known javascript framework especially for implementing charts in our project so chart.js is basically a simple engaging html based javascript library it has loads of different type of shots let us go ahead and visit the website so here's the website it has if you notice it has it has very wonderful and advanced level of charts which can which you can use it and the implementation is very simple and that is the reason i decided to release a video which which actually shows this implementation of chat in a very simplified way so click on get started i'll just show you what is there in the store so first of all we have the installation now this is since it's a java javascript page framework you need to include that reference in your project so reference can be installed by using the node package manager you can install it if you look at the installation page you can use the node package manager install it you can use the cdn you can refer this the reference of the chat in your project and you you can also download it from the github so for now what are we going to do is that we are going to refer this in our project directly but you can also add it and you know save it offline in your project so so creating chart as follows this for following uh you know structure of this implementation so it has a canvas object which actually is l for drawing elements so it has a canvas object and it has an id and the width that you like to hold then it has a script object and then it creates an instance of the chart and then it has various properties like you know type of charts like it is a it's a bar chart line chart and then data tag which has the labels uh and the color of the labels and data set which actually holds actuator now in this they have hard hardcoded this data and they've also given the background color with some additional options now there are loads of things to explore in this it's just not this code if you go to the different charts up you can see this area chart is there and what parameters to be used and how does it look if you go to general tab you can see all these parameters and options are available so you can use see these are the these this is a different types of chats that you can use it so um without uh wasting or you know without getting more into this let's go and do that implementation so what are we going to do if you go to the installation page okay you can see that um if you go to this if you go to chat js i just show it to you okay this is if you click on get getting started and then you can get to this page where they have shown you how to create a canvas object and then refer this i'm going to refer this library in our project so we go to our uh page that is view show sales record the first thing we are going to do is that we are going to refer the common layout of the project use slash slash underscore layout dot cs so this view will be referring to our common layout which is there in views shared and this is a layout page so this is a masterpiece where it has all the link of javascript so basically if you want you can either copy the link over here refer that link over here or you can also refer the link in the common place that is going to your shared layout and in your render body just our render body you can paste this so both the ways you can do it so our view will first refer this and now i'm going to show a quick implementation like you know before we connect our database and fetch records from database we will try to just copy and paste this code and show the things in action just copy this from this area because we are okay so this is a canvas first you need to copy the canvas and just so this will hold the canvas like you know it's a very bigger size so just reduce it and then you copy the script and paste it just below our reference so let's see this is action i'll also do one thing i'll just add this link into our common layout page so that is easy to know access it so go to your layout page and remove this controller oh and add sales record because this and then instead of index click on show sales let's also name it instead of home let's say scenes records sales progress yes ok so there is some exception okay forgot to add one more panel so this is done so fine so our project is loaded let's click on sales program and see the static graph c you can see the graph is loaded opposite very big size and i'll just try to change and show remove this and style so i'll just refresh it yes so you can see it is now quite i think this so in the start i mentioned about adding the runtime so added the random only because of this purpose when you might make any changes in the razer pages and save it you're able to just refresh it and you can see the changes so this is what the graph which we implemented just directly from the sample code but now our task is to fetch the data from this database and then dynamically render the charts and also provide an option to generate various types of charts so let's get started so we will use the same code and we'll modify it the first thing we will have to do is that fetching of the data now since this is a html based code we have to use ajax call and fetch the data and then bind the data in our chats instead of hard coding it like i've shown in this sample so let's go to a controller class and create code to fetch the data okay guys so let's first add the mechanism it will be a http post method and we are going to say public list object i'll tell you why we are going to use the list object because we need data in the x-axis as well as y-axis so there are two data sets required so we will use the list object and say get get sales data this is a method and we are going to now write code but before we write the code let's refer the database requirement so we say sales data dot data layer using sales data dot model class these tools are required let's define the db contest layer so let's say private read only says underscore context this is a contest class and then we are going to create a constructor generate constructor and we will use so we are passing this connection db context connection string in a constructor and initializing it now we come to our method and we say list object data this is the main data that we will be having multiple dataset the first is the the x-axis which is required to show the labels so we call it as labels this will dynamically come from the database so so basically if you go to a database we have this this should be displayed in our one of the axis and this should be displayed in another access so that based on the combination our charts will be plotted so this should be dynamic obviously because we are showing for the demo purpose but tomorrow if you have a dynamic data set still you will be able to manage this code so we say labels and we say underscore context dot our table name sales data now select so we need to select only the month name so we say lambda expression and p dot says month name to list this will hold only and then we add this to our labels dataset so there's one dataset prepared let's create a second data set now this will be int and this will be sales number and this will be the same but instead of the sales month name it will be sales number total says right and then we add this into our data table and finally we return the data we return the data so code is ready okay right now the code just not party passing on any parameters which will gradually upgrade so we come back to our show data dot c html now here we need to use an ajax call so make sure before you use any ajax call go to a layered layout page and if you see there is in the footer we have this we require to add the jquery min you just copy it either you can paste it on this page here or you can go to the layout just before the render body bases okay so now we'll be able to call ajax and fetch the data so what we are going to do is that we are going to remove this entire code we will going to keep this canvas canvas is required and the canvas id is my chart okay this reference to our chart.js is required so we are going to remove this block so we are going to create a dynamic block where we have the type data and instead of all this hard coding will fetch it from the database so let's remove this okay now what are we going to do is that we are going to create one more code so we want to make sure that when you click on the button then basically you should be able to show the data so okay so here i'm creating a button input id id and value show graph and type this button fine now what are we going to do is at the moment we click the button we are going to call the ajax make an ajax request to the database fetch the data and bind to the create instance of my chart and then provide the required set in the in the format required to generate a chart so let's do that so we are going to say let's also add type over here i just it's it's a better it's a good idea to mention the type now let's go ahead and add the function so i'm adding a function and and i'm going to create a event hash id and then i click function okay so now this becomes our structure so on the click what is going to happen on the click we are going to call it ajax method dollar sign as x okay and now we say type colon and this should be a post comma url this will be our controller name that will be sales record this one sales record and function name get sales sales record slash texas comma data so data is nothing it basically it's not having any parameter if you had any parameter to be passed with getsetter you could have passed it over here and then you have the content type colon and this is applications like json set right enter and data type is json comma now success now what should happen on success you are calling one more method called on success result and obviously there can be error so you say error so an error on error so this is our code for calling an ajax method now once our method is called okay on success method so we just write a function function and on success whatever data is returned okay so should we should we go ahead and test our ajax method first so let's do that instead of first writing the code of the chart let's go and see whether our adjacent successfully calling our method okay we put a breakpoint over here so that when we click on the button our method should be calling and we should be able to also check whether the properly data is loaded in our list object i hope guys you are liking this video i request everybody to like this video and also do subscribe my channel and share my channel with your friends so yeah the project is loaded click on sales progress now let's click on show graph yes so our ajax code is proper let's see whether the data is getting loaded yes so now it is fetching or calling okay yes so now if you can see we were able to fetch the month and now we add that into a list optic and then we will able to also fetch the sales so our list object will have two dataset for required for x axis and y axis so yes so this is successfully getting on let's go ahead and next step add code for fetching the data set as i mentioned in my earlier uh section that it this will be the same structure which will have to follow type data and then the labels and the data but in this case they have hardcoded it just to show a sample we are going to fetching the data from the record so now our on success result as data in list object the first thing we need to do is create a variable for assign the labels and the records separately so we say ran underscore data and this will assign this data to over here then where underscore data labels let's call it chat chart labels now underscore data and you pass index 0 so this will pass in the labels month jan feb march april etc now similarly we define one more variable called where underscore chat data this is the actual series number we say underscore data and we pass index one so we have loaded our data now now it's time to color our uh the chat legends so where our colors oh let's call it legend i think so for simplicity let's follow our colors and then so we have six objects over here like six is like no you need to jan feb march april so we will just for now set a color for them so we say red green blue [Music] orange and then brown blue okay so we have defined the color of all edges now let's go ahead and actually create the actual code for generating the chart so we say so we have a campus id just canvas id called the my chart so we are going to create an instant so new char chart and we have new chart and we are going to pass this id which we created which will render the graph okay and now we say comma enter and then first you say type here we say bar chart so we are creating a bar chart by default comma data color open parenthesis and pass labels color and here this will be your chart labels comma and now your data sets colon and box parenthesis now you say background color cooler and then your colors for edges comma finally data so here you your chart data goes over here and then you close this last so this is your this is your code to render the chart and we can go ahead now and check the code so we check this the data is getting called list object is getting populated successfully now it comes over here first since we have to segregate the labels and later that we did it over here then we set the color of our bars and then we create a new instance of the chart we say type bar as of now we will see in the latest session how to dynamically pass variable over here and then finally we have the data tag which actually takes a label data dynamically and then also passes the date actual data dynamically from the function call in the ajax so this is a small simple code now let's see things in action click on sales progress now click on show graph so this is our data which will be called i'm reviewing the breakpoint and executing the project okay so is something wrong this is a chart data this is a label and this is a legend so let's add a breakpoint and see what went wrong over here okay let's do one thing let's go to us console click on sales graph click f12 just to see what is the problem click on console so let's refresh once and see what is the error we are getting so if you notice we are not getting any error on success result and data is passed over here data is passed over there and chart labels and chart data let me just add a breakpoint to it alert underscore data data okay now let's refresh click on ok now i think the button click is working and let me add a lot over here this is getting called whether this method is getting called let us just check let's refresh it and now i think so success method is not getting called so there's some the success method is not getting called so this is json because i got the issue i just misspelled the its success s u c c e s s so this was the issue so let's remove this and try to run it again it's not required i click on save now let's refresh it let's add refresh it once and click on show graph yes you can see so i've successfully loaded the graph let's set the alignment properly the the width is let's make it 600 pixel it is okay just refresh it yes so we can see the graph is successfully loaded and if i make any changes in the database it will reflect over here so if i make this to three thousand three thousand and i make this to say ten thousand and refresh it once and then come over here and just refresh it show graph you can see the changes is reflecting over here so it's dynamically loading it now the thing is that if you want to add a feature where you can say i want to load a bar chart a pie chart a donut chart and you know line chart how do we do that for that what we need to do is that we need to create code in javascript that will actually fetch select give option for the customer to select the type of chart and accordingly pass that over here in the type section let's do that for that we require some html code to be changed so that we give an option to the customer so already have the code i'll just so this is a code i'll just copy this so instead of this button which i created i copy this code and explain the code to you guys so this is nothing we i'm just adding a div and adding a label called select chart type and now in the option i'm giving this following drop down option i'll create an html object called select and i'm passing bar line pi and don it okay and the button id is the same and then the canvas is also the same now what i do at the html end is that here on success okay once i pass in all the data i will fetch in the type of chat selected by the user so so here on id on click of id i'm going to write a code chart chart type dollar sign and ash let's say chat type chat type is the name of the drop down which i gave so this is a name of the topic id chat type okay and i select this object so once i have the chart up with me what i'm going to do is that pass in the same value in my code so i come over here and remove this and just pass this with it let's see things in action guys if you haven't subscribed my channel yet i request everybody to subscribe my channel so yeah the page is loaded now click on sales progress now you can see there's an option called chart type i select bar and then i click on show graph okay now i select line and click on sugar you notice it is not refreshing so i'll just do an art refresh and now i select line it'll show the line chart similarly click on add refresh and then i click on pi it will show the pi so every time i as a user i will not be able to refresh it so we'll have to write a small piece of code over here so that it dynamically renders it whatever option is selected by the user so for that i found only one way i tried doing a very simple um option by just resetting that html container the content that is canvas container but it was not happening so what i did is that i actually recreated this can canvas container every time when the user create clicked on the button so i'll show you the code so what i did is that this was a the container id that is my chart so here i did so i remove this because this will not get dynamic this height and dimension i just kept this my id i went over here and i said where and the id when you click on the button you said chat view document dot get element id and i pass this id my chat so so so this is what i did is i'll also have to create a dim over here i miss this point so we are saying chat view okay now inside this chat view div i add the canvas now so what i did is that i clicked on this chat view container div and i fetched this on the click of this button and then i said chat view dot inner html a positive space and then i recreated it chat view dot append and i recreated the this one my chat canvas over here and this id equals to my chart make sure you keep the same name as my chart max height is 400 pixel then close the bracket and then and close it and canvas so they say dynamically created it [Music] so you notice this code what it does is that it has created a div and inside the drive it has that created the canvas each time when you click on the button it will first first fetch the chat view div id then it will clear the dave id okay so whatever is said that it is it will not be no it's basically removing it and then it creates it appends the same canvas id inside the div that is the chat view with the same name which i have referred in my chat id and it provides the dimensions also so this is how i created to dynamically you know reflect the selection of the user now let's go ahead and check the things in action click on sales progress and select bar chart click okay so let me just check what is the problem invalid token line 53 so chat view get element chat view so this is a chat type this is working fine then i say chat view is document dot get element id and a chat view which is our id over here okay then chat view dot inner html this is also fine and then chat view append canvas id my chart style colon then colon i don't think this is required now let me just check invalid or unexpected token 75 so there is some error over here and let me comment this for a moment just to identify whether this is an error that is creating a issue in the code now you got it got it so this is [Music] so basically we have to just revisit the code that is actually appending so let's find it out it's div div ide and this is chart view and then there's a canvas and canvas id which seems good now we come back to our code this fetches its selection and then we have chat view so i have identified the issue so issue was that this code is proper it is fetching the type it's fetching the this chat view container and then it is actually you know adding a space to it removing the canvas id from here now then it appends it but here i missed out a single code so this this i missed out over here and i just wanted to show that while you are working be careful on this because of the single quote means i was facing this error now the code should work i just start the code again project again click on sales progress we select bar and show okay so here one refresh and select bar and click on show yes it is showing a bar chart now you select line chart click on it shows a line chart you select buy it shows a pie chart you select on it and it selects it on its chart so now you are able to see that dynamically it is generating the records now if you look at the code once again i'll just enlarge the code area and remove the space fire which i used for debugging so this is your html code where you are giving options for customer to select the type of chat you want to generate this is your canvas initially we had a single canvas but then in order to refresh it on the selection of the type of chart we had to create a div id on and place the canvas inside it so that we can you know reset it and epit the canvas every time when you click on the button this is your chart.js reference we can store it offline also and this is actually your main javascript code where on click of the button you are selecting the type and also you're refreshing the canvas area then you're calling an ajax method and fetching the data in list object then on success you are actually assigning the data and this is the actual code which appends the data dynamically in your graph object and generates the graph so type of graph which comes dynamically and data it populates the label and then the color and the data object and the end result is this beautiful output which we can see and use it in your projects with confidence and how to implement it in a very simple and easy language i hope guys you like this video please do like and share my videos subscribe my channel share it with your tech buddies your friends your relatives and help me to grow the channel so that everybody benefited by looking at and learning all these new things an easy implementation of all the concepts thank you for your time
Info
Channel: Digital TechJoint
Views: 28,415
Rating: undefined out of 5
Keywords: mvc, mvcpattern, dotnetframework, dotnet, aspnet, asp, aspnetcore, aspcore, visualstudio, visualstudio2022, dependencyinjection, mvcrouting, routing, learnmvc, learnaspnet, aspnetcourse, entityframework, aspnetwebapplication, dotnet6, developer, programming, learnprogamming, microsoftvisualstudio, csharp, razorpages, tutorial, c#, dbcontext, .net, simplilearn, html, c sharp, learn asp.net, what is asp.net, what is mvc, coding, bootstrap, crash course, course, chart, chartjs, javascript, working with charts, ajax, ajax call
Id: 2Zag_ejvL4c
Channel Id: undefined
Length: 57min 27sec (3447 seconds)
Published: Sun Jun 05 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.