0

How can I show month names in my view instead of month numbers?

Action Method:

public ActionResult MyPerformance()
{
    int year = DateTime.Now.Year;
    DateTime firstDay = new DateTime(year, 1, 1);
    DateTime lastDay = new DateTime(year, 12, 31).AddDays(1).AddSeconds(-1);

    var result = db.Chats
        .Where(c => System.Data.Entity.DbFunctions.TruncateTime(c.MSTChatCreatedDateTime) >= firstDay &&
                    System.Data.Entity.DbFunctions.TruncateTime(c.MSTChatCreatedDateTime) <= lastDay)
        .Select(x => new { x.MSTChatCreatedDateTime })
        .ToList()
        .GroupBy(c => new
        {
            Year = c.MSTChatCreatedDateTime.ToCleanDateTime().Year,
            Month = c.MSTChatCreatedDateTime.ToCleanDateTime().Month
        })
        .Select(c => new ReportVM
        {
            Title = string.Format("{0}", c.Key.Month),  //chart x Axis value.
            ChatCountCreatdDate = c.Count() //chart y Axis value.
        })
        .ToList();

    return View(result);
}

Data being reflected is correct in the View, but I am not able to render the month names in the view.

See the attached Image showing the month numbers.

Showing Month Numbers instead of Month Names

Thank you!

Tawab Wakil
  • 1,737
  • 18
  • 33
R S
  • 27
  • 4
  • Does this help?: https://stackoverflow.com/questions/6286868/convert-month-int-to-month-name – Tawab Wakil Jun 13 '21 at 02:56
  • Thank you! I did fix it by adding a extension method and calling the Name in View from the Extension method. – R S Jun 13 '21 at 17:58

1 Answers1

0

You can format in "MMM" which display name, here is your code

public ActionResult MyPerformance()
{
    int year = DateTime.Now.Year;
    DateTime firstDay = new DateTime(year, 1, 1);
    DateTime lastDay = new DateTime(year, 12, 31).AddDays(1).AddSeconds(-1);

    var result = db.Chats
        .Where(c => System.Data.Entity.DbFunctions.TruncateTime(c.MSTChatCreatedDateTime) >= firstDay &&
                    System.Data.Entity.DbFunctions.TruncateTime(c.MSTChatCreatedDateTime) <= lastDay)
        .Select(x => new { x.MSTChatCreatedDateTime })
        .ToList()
        .GroupBy(c => new
        {
            Year = c.MSTChatCreatedDateTime.ToCleanDateTime().Year,
            Month = c.MSTChatCreatedDateTime.ToCleanDateTime().Month
        })
        .Select(c => new ReportVM
        {
            Title = c.MSTChatCreatedDateTime.ToCleanDateTime().ToString("MMMM"),  //chart x Axis value.
            ChatCountCreatdDate = c.Count() //chart y Axis value.
        })
        .ToList();

    return View(result);
}