TransWikia.com

Sorting DateTime column in ASP.NET MVC

Stack Overflow Asked by steven85791 on January 11, 2021

I have an ASP.NET MVC app where I have a column in a table that displays DateTime values from a MySQL database. The column gets sorted by string value instead of DateTime value. I need it to display like Friday, August 14th, 2020 05:13 PM.

I get it to display like this using

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:f}")]

I need it to sort by Date/Time. This is the code I have.

DataView:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:f}")]                               
public System.DateTime JobDateTime { get; set; }

Controller:

public ActionResult Index()
{
    return View(db.jobs.OrderByDescending(x=>x.JobDateTime).ToList());
}

Index view:

@Html.DisplayFor(modelItem => item.JobDateTime)`

I can’t figure out how to sort it and get it to display in long date format. I’ve only been able to get one or the other.

2 Answers

The MassDateTime property would be in a ViewModel (most probably). Let we call it as JobViewModel or adjust the name whatever you have given to it.

Then the field MassDateTime type should be string instead of DateTime as required to show on view in string format.

public class JobViewModel
{
    public string MassDateTime { get; set; }
}

No need to mention attribute on the property.

Now Index method would be like as:

public ActionResult Index()
{
    var data = db.jobs.
                 AsEnumerable().
                 OrderByDescending(x => x.JobDateTime).
                 Select(a => new JobViewModel
                    {
                        MassDateTime = a.JobDateTime.ToString("dddd, dd MMMM yyyy hh:mm")
                    }).ToList();

    return View(data);    
}

Correct answer by Sh.Imran on January 11, 2021

Sounds like DisplayFormat attribute is applied before sorting. In this case, you might want to remove it from the property definition, and put into your Linq query:

db.jobs.OrderByDescending(x => x.JobDateTime).Select(d => d.ToString("f")).ToList()

Or do that transformation in Razor, whichever suits you best.

Answered by Mike on January 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP