I have a dashboard right now that produces graphs and data from the database based on the current year. I am trying to add a dropdownlist of years and then have the graphs in the dashboard change on the year select. I have 2 areas that have to change and I am having issues with getting the variable for the year in the URL. I dont want to post the whole script because it is lengthy. My dropdown works fine, I just cannot use the variable in the string.
This is how it is currently setup:
Inside a $(document).ready(function () { }
SalesByMonth()
var Year = new Date().getFullYear()
$('#year').change(function () {
Year = document.getElementById("year").value;
$("#year").val(" ");
console.log(Year);
});
function SalesByMonth() {
var Year = new Date().getFullYear()
$.ajax({
url: '@Url.Action("GetChartData", "Dashboard", new { Year = "Year" })',
The variable "Year" is not seen by the function. Even if I put it in the function SalesByMonth
After doing some searching I figured out what works. First in my CHTML page I had to put this:
@{ var dates = DateTime.Now.Year.ToString(); }
Because I could not get the JavaScript getFullYear() to work at all. It was always null. No matter how I tried to do it. Then I got my variable like this with the select function right below it:
var currentYear = @dates;
$('#year').change(function () {
currentYear = document.getElementById("year").value;
$("#year").val(" ");
console.log(currentYear);
SalesByMonth();
Revenue();
});
Here is my selectlist:
<div class="form-group sol-container">
@Html.DropDownList("Year", null, new { @class = "sol-container-selection", id = "year" })
</div>
Then in my ajax url I had to do this:
url: '@Url.Action("GetChartData", "Dashboard", new { Year = "year" })'.replace('year', currentYear),
The call to SalesByMonth and Revenue functions in the .change function refreshes the charts with the current year.
And just to complete this to have the full code, here is my controller for the dropdown list.
AccountingEntities acct = new AccountingEntities();
var list = acct.Transaction.Select(s => s.TransactionDate.Year).Distinct().OrderByDescending(s => s).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() });
ViewBag.Year = list.Select(x => new SelectListItem
{
Value = x.Text,
Text = x.Text
}).ToList();