如何改造MVC.NET控制器以获取指定车辆油耗数据绘制图表
Fix for Showing Individual Fuel Consumption Records in Your MVC.NET Chart
Hey there! Let's get your chart displaying individual fuel records instead of repeated total sums. The issue with your current code is that you're looping through all distinct vehicle IDs and recalculating the total sum for your target vehicle every time—hence the 38 identical sum values. Here's how to adjust it:
Step-by-Step Explanation & Modified Code
First, we need to:
- Filter records by the specified vehicle ID and date range
- Pull individual
Volumevalues directly from matching records (no summing needed) - Pass both the fuel volumes and their corresponding dates to the view (so your chart has meaningful X-axis labels)
Here's the updated controller code:
public ActionResult Choice(string Snom, DateTime? date1, DateTime? date2) { // Handle null date parameters: default to earliest record date and current date if not provided DateTime startDate = date1 ?? db.Fuel.Min(f => f.Date); // Replace `Date` with your actual date column name DateTime endDate = date2 ?? DateTime.Now; // Fetch ONLY the records for the specified vehicle within the date range, sorted by date var targetFuelRecords = db.Fuel .Where(f => f.VehicleId == Snom && f.Date >= startDate && f.Date <= endDate) .OrderBy(f => f.Date) .ToList(); // Pass individual volume values for the chart Y-axis ViewBag.FuelVolumes = targetFuelRecords.Select(f => f.Volume).ToList(); // Pass corresponding dates (formatted as strings for easy frontend use) for the chart X-axis ViewBag.RecordDates = targetFuelRecords.Select(f => f.Date.ToString("yyyy-MM-dd")).ToList(); // Optional: Keep this if you still need the list of distinct vehicles elsewhere in the view // ViewBag.COMP = db.Fuel.Select(x => x.VehicleId).Distinct().ToList(); return View(); }
Key Changes Made:
- Removed redundant loops & sums: No more looping through all vehicles to recalculate the same total—we directly target the vehicle you specified.
- Added date range filtering: Properly handles optional date parameters so you only get data between
date1anddate2. - Passed date labels: Your chart will now show each record's date alongside its fuel volume, making the data meaningful instead of just random points.
- Sorted records: Ordering by date ensures your chart points appear in chronological order.
Quick Notes:
- Double-check that your
Fueltable's date column name matches what's in the code (replacef.Datewith your actual column name likeRefuelDateif needed). - In your view, when rendering the chart (e.g., with Chart.js), use
ViewBag.RecordDatesas the X-axis labels andViewBag.FuelVolumesas the data points.
内容的提问来源于stack exchange,提问作者Nellio
相关产品推荐
相关产品推荐

