The controller will have the methods that will call our data access layer methods to handle database operations.
Adding Views to the Application
We will create three view files,
- Index.cshtml
This view will display all the expense data and contains a search box to search for a particular item.
- _expenseForm.cshtml
This is a partial view, which contains the form to handle user inputs. This is used for both add and edit functionality and will be rendered in a modal dialog.
- _expenseReport.cshtml
This is also a partial view, which will show the expense summary in a bar chart using Highcharts. It is also rendered as a modal dialog.
Index View
To create the view file, right click on the Index method in our controller and select “Add View…”. This will open an “Add MVC View” dialog box. Put in the name of view as Index and click Add. Make sure that “Create as a partial view” check box is not checked. Refer to the image below,
This will create the Index.cshtml file inside “Expense” folder under the Views folder. Open Index.cshtml file and put in the following code,
Let us understand this code. At the top we have included the bootstrap and jQuery references. After that we have added two buttons for adding a new expense and for creating the expense summary. We have also included a form containing a search box to filter out the records. On clicking of “Filter” button, the form is submitted and it invoked the Index method in our controller which will return the items matching the search criteria. The search functionality is provided only on item name field.
We are using a table to display all the expense records in our database and each record has two action button corresponding to it – Edit and Delete.
We have also created two modal dialogs , one for adding/editing the expense data and another to display the expense summary report.
In the script section, we have defined AddEditExpenses function. This function will be invoked when “Add Expense” or “Edit” button is clicked. We are passing the itemId as parameter in this method. If the “ItemId” value is not set then it is considered as Add function and if the “ItemId” is set then it is an Edit function. We will call “AddEditExpenses” in our controller which will return the partial view “_expenseForm” and bind it to ExpenseReport model. The modal will be empty for “Add” call and contain the expense item data in case of “Edit” call. Since we are using bootstrap datepicker to select the expense date, hence we have set the datepicker properties on modal dialog load.
The ReportExpense function will call ExpenseSummary method in our controller, which will return the partial view “_expenseReport” to be displayed as a modal dialog. This partial view will display the monthly and weekly expense summary chart using Highcharts.
The DeleteExpense function is used to delete the record of a particular expense. This will invoke the “Delete” method in our controller to remove the expense record from our database.
We are also using dynamic binding to bind the submit event of “expenseForm” modal. This form is defined in “_expenseForm.cshtml” view. On submitting of form, we are invoking an ajax call to the “Create” method in our controller class. Since we are using same form for both Edit and Add functionality so we need to distinguish among both using the ItemId value. In the “Create” method of controller, we will check if the ItemId is set then we will invoke UpdateExpense method, else invoke AddExpense method. After successful submit, we will close the modal and redirect to Index view to show the updated list of expenses.
ExpenseForm View
This is a partial view that will be displayed in a modal dialog on clicking of “Add Expense” button in Index view.
To create the view file, right click anywhere inside our controller file and select “Add View…”. This will open an “Add MVC View” dialog box. Put in the name of view as ““_expenseForm” and click Add. Make sure that “Create as a partial view” check box is selected. Refer to image below,
Open the “_expenseForm.cshtml file” and put in the following code in it
- @model ExpenseManager.Models.ExpenseReport
-
- <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>
- <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css" rel="stylesheet">
-
- <div>
- <div class="row">
- <div class="col-md-8">
- <form id="expenseForm">
- <input type="hidden" asp-for="ItemId" />
- <div class="form-group">
- <label asp-for="ItemName" class="control-label"></label>
- <input asp-for="ItemName" class="form-control" />
- </div>
- <div class="form-group">
- <label asp-for="Category" class="control-label"></label>
- <select asp-for="Category" class="form-control">
- <option value="">-- Select Category --</option>
- <option value="Food">Food</option>
- <option value="Shopping">Shopping</option>
- <option value="Travel">Travel</option>
- <option value="Health">Health</option>
- </select>
- </div>
- <div class="form-group">
- <label asp-for="Amount" class="control-label"></label>
- <input asp-for="Amount" class="form-control" />
- </div>
- <div class="form-group" id="calender-container">
- <label asp-for="ExpenseDate" class="control-label"></label>
- <div class="input-group date">
- <input asp-for="ExpenseDate" type="text" class="form-control"><span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
- </div>
- </div>
- <div class="form-group">
- <button type="button" id="btnSubmit" class="btn btn-block btn-info">Save</button>
- </div>
- </form>
- </div>
- </div>
- </div>
At the top, we are including the cdn reference to the bootstrap-datepicker so that we can use it in our modal dialog. Then we have a form element, which binds to our modal. We also have a submit button which will post the form data to the Create method in our controller using ajax call.
ExpenseReport View
This is a partial view that is displayed in the modal dialog on clicking “Expense Report” button in Index view.
Create a new partial view ““_expenseReport.cshtml” and put in the following code in it.
- <script src="https://code.highcharts.com/highcharts.js"></script>
-
- <button id="btnMonthlyReport" class="btn btn-info">Monthly Report</button>
- <button id="btnWeeklyReport" class="btn btn-warning">Weekly Report</button>
- <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto">
-
- </div>
-
- <script>
-
- $(document).ready(function () {
- $("#btnWeeklyReport").click(function () {
- var titleMessage = "Expenses in last four weeks is : ";
-
- $.ajax({
- type: "GET",
- url: "/Expense/GetWeeklyExpense",
- contentType: "application/json",
- dataType: "json",
- success: function (result) {
- var keys = Object.keys(result);
- var weeklydata = new Array();
- var totalspent = 0.0;
- for (var i = 0; i < keys.length; i++) {
- var arrL = new Array();
- arrL.push(keys[i]);
- arrL.push(result[keys[i]]);
- totalspent += result[keys[i]];
- weeklydata.push(arrL);
- }
- createCharts(weeklydata, titleMessage, totalspent.toFixed(2));
- }
- })
- })
-
- $("#btnMonthlyReport").click(function () {
- var titleMessage = "Expenses in last six months is : ";
-
- $.ajax({
- type: "GET",
- url: "/Expense/GetMonthlyExpense",
- contentType: "application/json",
- dataType: "json",
- success: function (result) {
- var keys = Object.keys(result);
- var monthlydata = new Array();
- var totalspent = 0.0;
- for (var i = 0; i < keys.length; i++) {
- var arrL = new Array();
- arrL.push(keys[i]);
- arrL.push(result[keys[i]]);
- totalspent += result[keys[i]];
- monthlydata.push(arrL);
- }
- createCharts(monthlydata, titleMessage, totalspent.toFixed(2));
- }
- })
- })
- })
-
- function createCharts(sum, titleText, totalspent) {
- Highcharts.chart('container', {
- chart: {
- type: 'column'
- },
- title: {
- text: titleText + ' ' + totalspent
- },
- xAxis: {
- type: 'category',
- labels: {
- rotation: -45,
- style: {
- fontSize: '13px',
- fontFamily: 'Verdana, sans-serif'
- }
- }
- },
- yAxis: {
- min: 0,
- title: {
- text: 'Money spent'
- }
- },
- legend: {
- enabled: false
- },
- tooltip: {
- pointFormat: 'Total money spent: <b>{point.y:.2f} </b>'
- },
- series: [{
- type: 'column',
- data: sum,
- }]
- });
- }
-
- </script>
On the top we have included the cdn reference to Highcharts. We have also provided two buttons to view the monthly reports of the last six months and weekly reports for the last four weeks. The report will be generated as a bar chart to provide a comparative study of expense summaries.
On click ing the weekly report button, we will invoke the GetWeeklyExpense method of our controller that will return the data in Json format and we will pass this to createCharts function to create the weekly expense bar chart using Highcharts.
Similarly, we will invoke GetMonthlyExpense method of our controller on clicking of “Monthly Report” button and pass the Json result to createCharts function to create the monthly expense bar chart using Highcharts.
Configure route URL
Open Startup.cs file to set the format for routing.Scroll down to app.UseMvc method, where you can set the route url.
Make sure that your route url is set like this
- app.UseMvc(routes =>
- {
- routes.MapRoute(
- name: "default",
- template: "{controller=Expense}/{action=Index}");
- });
This url pattern sets ExpenseController as default controller and Index method as default action method. Default route parameters need not be present in the URL path for a match. If we do not append any controller name in the URL then it will take ExpenseController as default controller and Index method of ExpenseController as default action method. Similarly, if we append only “/Expense” to the URL, it will navigate to Index action method of Expense controller.
Execution Demo
Press F5 to launch the application. You can see a page similar to the one shown below.
Here we have “Add Expense” button to add a new expense report. The “Expense Report” button will open a dialog box to show the bar chart of monthly and weekly expense data. On the top right corner, we have a search box to search the records using item name.
Look at the below Gif image for the demo of application.
Conclusion
We have succesfully created a personal expense manager application using ASP.NET Core and Entity Framework Core with the help of Visual Studio 2017 and SQL Server 2017. We have also used Highcharts to create a bar chart for monthly and weekly expense summary.
Please download the source code from GitHub and play around to get a better understanding.
You can read my other articles on ASP .NET Core here