How to call datetime column on your controller in asp.net mvc?

Gcobani Mkontwana 21 Reputation points
2021-09-23T06:46:51.237+00:00

Hi Team

I have the code, but my logic needs some improvements meaning i want to find a way to call datetime column from my database not hardcode cz it makes it difficult to do changes. Let me share my logic below;

// Controller.cs
public JsonResult GetAll()
{
return Json(DashboardTimeLine(), JsonRequestBehavior.AllowGet);
}

    public List<Dashboard> DashboardTimeLine()
    {
        List<Dashboard> timeList = new List<Dashboard>();
        timeList.Add(new Dashboard { Incident = 1, FromDateTime = new DateTime(2021, 09, 23, 08, 01, 43), ToDate = new DateTime(2021, 08, 10, 15, 23, 48) });
        timeList.Add(new Dashboard { Incident = 2, FromDateTime = new DateTime(2021, 09, 23, 07, 05, 15), ToDate = new DateTime(2021, 08, 23, 07, 05, 49) });
        timeList.Add(new Dashboard { Incident = 3, FromDateTime = new DateTime(2021, 09, 23, 07, 05, 15), ToDate = new DateTime(2021, 07, 15, 05, 56, 10) });
        return timeList;
    }

// Model.cs
public int Incident { get; set; }

    public DateTime FromDateTime { get; set; }

    public DateTime ToDate { get; set; }


    public string Resources { get; set; }


    public string Description { get; set; }


    public int EndDate { get; set; }
}
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,672 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,561 Reputation points Microsoft Vendor
    2021-09-23T09:53:11.993+00:00

    Hi @Gcobani Mkontwana ,

    i want to find a way to call datetime column from my database not hardcode cz

    To access data from the database, you could refer the following article/tutorial to use EF core:

    Getting Started With Entity Framework Core - ASP.NET Core

    Creating a Model for an Existing Database in Entity Framework Core

    Tutorial: Get started with EF Core in an ASP.NET MVC web app

    then you can access the data via the DbContext, code like this:

    public async Task<IActionResult> Index()  
    {  
        return View(await _context.Students.ToListAsync());  
    }  
    

    Besides, for the datetime property, if you don't want to hardcode, you could also set the default value, check this article.

    If I misunderstand your question or is there any unclear about my reply, please let me know freely.


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.