Hello,
This is my first try at MVC Core.
I have a table with datetime data type. I have defined the model for this table.
When I declare the property in the model as datetime, the model does not show any records.
When I declare the property as string, the model shows data, but then then the context returns invalid cast from datetime to string error.
Kindly guide.
Thanks.

Pankajkumar PatelRank #181 · 13.4K reputationPosted Dec 9, 2022, 12:25 AM EST
Hi Shailesh Bist,
This is one of the good link with practical example:
Hope this will help you!
Pankajkumar PatelRank #181 · 13.4K reputationPosted Dec 9, 2022, 1:10 AM EST
Display DateTime value in dd/mm/yyyy format in Asp.NET MVC
Hope this will help you!
Sachin SinghRank #66 · 26.2K reputationPosted Dec 9, 2022, 3:17 AM EST
On view page do this
Shailesh Bist20 reputationPosted Dec 9, 2022, 12:41 AM EST
Hi Pankaj,
Thanks for the information. I checked the link. This is when we post data.
In my case, I am not posting anything. This is just a view page. Will it work for this view also?
Thanks.
Vishal JoshiRank #377 · 6.7K reputationPosted Dec 9, 2022, 4:14 AM EST
Hello Shailesh
Please try the below code to work with the date in MVC.
//Model [Required(ErrorMessage = "Enter the issued date.")] [DataType(DataType.Date)] public DateTime IssueDate { get; set; } // Razor Page Or View @Html.ValueFor(model => model.RegistrationDate, "{0:dd/MM/yyyy}") //Web.ConfigShailesh Bist20 reputationPosted Dec 9, 2022, 6:44 AM EST
Hi Vishal,
Thanks for the response.
My context code is as below.
public class ApplicationDbContext : DbContext options) : base(options)
{
public ApplicationDbContext(DbContextOptions
{
}
public DbSet RAJ_AAJ_KA_SHABDH { get; set; } RAJ_DAILY_SHABD { get; set; }
public DbSet
}
My controller code is as below.
public async Task Index()
{
List AAJ =await _db.RAJ_AAJ_KA_SHABDH.ToListAsync();
HomePageVM VM = new HomePageVM()
{
DailyHindi = GetHindiText(_db.RAJ_AAJ_KA_SHABDH.Find(_db.RAJ_DAILY_SHABD.FirstOrDefault().Sr_No).Hindi_Description.ToString()),
DailyEnglish = _db.RAJ_AAJ_KA_SHABDH.Find(_db.RAJ_DAILY_SHABD.FirstOrDefault().Sr_No).English_Description.ToString(),
};
return View(VM);
}
When I declare the property as datetime, the code highlighted in red gives errror because the dbset is null.
When I declare the property as string, then I get string to datetime conversion error in the code highlighted in yellow.
Regards