【问题标题】:Show data week wise for current month in ASP.Net MVC在 ASP.Net MVC 中按周显示当前月份的数据
【发布时间】:2021-05-17 03:20:17
【问题描述】:

如何显示当月每周的数据?使用我当前的代码,我只能显示上周、本月或本周的数据。但我正在努力编写一个可以显示当前月份数据的代码,按周显示。

例子

Week1 = QAScore 94%(Average)
Week2 = 95%
Week3 = 90%
Week4 = 91%

模型类如下

public String Title { get; set; }
public DateTime? CreatdDate { get; set; }
public int ChatCountCreatdDate { get; set; }

动作

public ActionResult DisplayChart()
{
//initial data.
//List<Chat> orderlist = new List<Chat>();
        
//based on the year month and week, group the order, and get the weekly report.

    var result = db.Chats.ToList().GroupBy(c => new
            {
                Year = c.MSTChatCreatedDateTime.ToCleanDateTime().Year,
                Month = c.MSTChatCreatedDateTime.ToCleanDateTime().Month,
                WeekofMonth = c.MSTChatCreatedDateTime.ToCleanDateTime().GetWeekOfMonth()
            }).Select(c => new ReportVM
            {
                Title = string.Format("{0}/{1}/Week{2}", c.Key.Year, c.Key.Month, c.Key.WeekofMonth),  //chart x Axis value.
                ChatCountCreatdDate = c.Count() //chart y Axis value.
            }).ToList();

//return the data to the view.
return View(result);
}

查看

@model List<TicketTool.Models.VM.ReportVM>
@{
ViewBag.Title = "DisplayChart";
}
<meta name="viewport" content="width=device-width" />
<h2>DisplayChart</h2>
@{
var chart = new Chart(width: 500, height: 500, themePath: "MyTheme.xml")
            .AddTitle("Order Distribution")
            .AddSeries("Order", chartType: "Column",
            xValue: Model, xField: "Title",
            yValues: Model, yFields: "ChatCountCreatdDate")
            .Write();
    
    }

以上是我展示数据的操作方法。

【问题讨论】:

  • 请不要将这样的随机单词大写。读这样的文字很烦人。

标签: asp.net-mvc asp.net-core asp.net-mvc-4


【解决方案1】:

终于得到了这个功能,并使用下面的代码显示当前月份的每周数据。在这里更新,方便其他人使用

public ActionResult DisplayChart()
{
/*This Month Begin*/

DateTime now = DateTime.Now.AddDays(-3);
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
/*This Month Ends*/


var result = db.Chats.Where(c => System.Data.Entity.DbFunctions.TruncateTime(c.MSTChatCreatedDateTime) >= startDate &&
System.Data.Entity.DbFunctions.TruncateTime(c.MSTChatCreatedDateTime) <= endDate).Select(x => new {x.MSTChatCreatedDateTime}).ToList().GroupBy(c => new 
{ 
Year = c.MSTChatCreatedDateTime.ToCleanDateTime().Year,
Month = c.MSTChatCreatedDateTime.ToCleanDateTime().Month,
WeekofMonth = c.MSTChatCreatedDateTime.ToCleanDateTime().GetWeekOfMonth()
}).Select(c => new ReportVM
{
Title = string.Format("{0}/{1}/Week{2}", c.Key.Year, c.Key.Month, c.Key.WeekofMonth),  //chart x Axis value.
ChatCountCreatdDate = c.Count() //chart y Axis value.
}).ToList();
//return the data to the view.
return View(result);
}

【讨论】:

    【解决方案2】:

    要获取周报,我们可以根据日期时间值获取年、月和 WeekOfMonth。

    您可以使用以下代码创建一个 DateTimeExtensions,它将根据特殊日期时间获取月份中的星期几。

    public static class DateTimeExtensions
    {
        static GregorianCalendar _gc = new GregorianCalendar();
        public static int GetWeekOfMonth(this DateTime time)
        {
            DateTime first = new DateTime(time.Year, time.Month, 1);
            return time.GetWeekOfYear() - first.GetWeekOfYear() + 1;
        }
    
        static int GetWeekOfYear(this DateTime time)
        {
            return _gc.GetWeekOfYear(time, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
        }
        static DateTime ToCleanDateTime(this DateTime dt)
        {
            return new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0, 0);
        }
    
        public static DateTime ToCleanDateTime(this DateTime? dt)
        {
            if (dt.HasValue)
            {
                return dt.Value.ToCleanDateTime();
            }
            return DateTime.Now; // if dt doesn't have value, return current DateTime.
        }
    }
    

    如何在 View 中显示上述代码?请帮忙

    根据您的代码,您似乎想使用图表显示结果。如果是这种情况,请尝试使用Chart Helper

    请参考以下示例:

    Models:OrderModel 是Database 实体,OrderModelVM 用于将数据从控制器传输到视图和显示图表。

    public class OrderModel
    {
        public int OrderId { get; set; }
        public string ShipCity { get; set; }
        public int TotalOrders { get; set; }
    
        public DateTime? CreateDateTime { get; set; }
    }
    public class OrderModelVM
    {
        public String Title { get; set; }
        public int TotalOrder { get; set; }
    }
    

    控制器(使用 DateTimeExtensions 方法分割日期时间):

        public ActionResult DisplayChart()
        {
            //initial data.
            List<OrderModel> orderlist = new List<OrderModel>()
            {
                new OrderModel(){ OrderId=101, ShipCity="T1",TotalOrders=89, CreateDateTime = new DateTime(2021, 2, 2)},
                new OrderModel(){ OrderId=102, ShipCity="T2",TotalOrders=92, CreateDateTime = new DateTime(2021, 2, 9)},
                new OrderModel(){ OrderId=103, ShipCity="T3",TotalOrders=98, CreateDateTime = new DateTime(2021, 2, 16)},
                new OrderModel(){ OrderId=104, ShipCity="T4",TotalOrders=99, CreateDateTime = new DateTime(2021, 2, 13)},
            };
            //based on the year month and week, group the order, and get the weekly report.
            var result = orderlist.GroupBy(c => new
            {
                Year = c.CreateDateTime.ToCleanDateTime().Year,
                Month = c.CreateDateTime.ToCleanDateTime().Month,
                WeekofMonth = c.CreateDateTime.ToCleanDateTime().GetWeekOfMonth()
            }).Select(c => new OrderModelVM
            {
                Title =  string.Format("{0}/{1}/Week{2}", c.Key.Year, c.Key.Month, c.Key.WeekofMonth),  //chart x Axis value.
                TotalOrder = c.Sum(d => d.TotalOrders) //chart y Axis value.
            }).ToList();
    
            //return the data to the view.
            return View(result);
        }
    

    查看页面:使用图表助手显示报表。

    @model List<NetMvcSample.Models.OrderModelVM>
    @{
        ViewBag.Title = "DisplayChart";
    }
    <meta name="viewport" content="width=device-width" />
    <h2>DisplayChart</h2>  
        @{
            var chart = new Chart(width: 500, height: 500, themePath: "MyTheme.xml")
                .AddTitle("Order Distribution")
                .AddSeries("Order", chartType: "Column",
                xValue: Model, xField: "Title",
                yValues: Model, yFields: "TotalOrder")
                .Save("~/Images/Chart01.png", "png");
            //.Write();
    
        } 
    
        <img src="~/Images/Chart01.png" />
    

    [注意]在这个示例中,我们应该在根目录下创建一个Images文件夹。

    Views/Home 文件夹中添加一个 MyTheme.xml 文件。该文件用于配置图表,下面的代码用于显示y轴值。

    <?xml version="1.0" encoding="utf-8" ?> 
    <Chart>
      <ChartAreas>
        <ChartArea Name="Default">
          <AxisX>
            <MajorGrid Enabled="false"></MajorGrid>
          </AxisX>
        </ChartArea>
      </ChartAreas>
      <Series>
        <Series Name="Order" IsValueShownAsLabel="true"></Series>
      </Series>
    </Chart>
    

    结果如下:

    更多关于在asp.net MVC中使用图表的详细信息,请参考以下文章:

    Create Charts (Column Charts) from Database using Charts Helper in ASP.Net MVC

    How to add values to the top of column in MVC5 Chart?

    Displaying Data in a Chart with ASP.NET Web Pages (Razor)

    【讨论】:

    • 感谢您的回复,抱歉无法立即测试。使用上述操作方法“DateTime?不包含 GetWeekOf Month 的定义”时出现错误。这是代码 var result = db.Chats.Select(x => new { Year = x.MSTChatCreatedDateTime.Year, Month = x.MSTChatCreatedDateTime.Month, WeekofMonth = x.MSTChatCreatedDateTime.GetWeekOfMonth() });请帮忙
    • 嗨@RiyazShaikh,你有没有添加过静态类DateTimeExtensions? GetWeekOfMonth 方法在这个类中。
    • 是的,我确实这样做了
    • 嗨@RiyazShaikh,检查this thread,尝试将可空日期时间更改为日期时间类型。
    • 使用 DateTImeextention 方法更新我的第一个响应
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多