Reputation: 679
I want to retrieve datetime from database and want to display in View. When I submitted the form, date stored in this format 2018-08-06 15:31:16.707
and I use some JQuery to get that date and it is currently showing in Mon Aug 06 2018 15:31:16 GMT+1200 (New Zealand Standard Time) {}
. I want to show datetime exactly what is stored in database.
Controller
[HttpPost]
public JsonResult _Update(EmpViewModel model)
{
try
{
var Getadvert = context.Employee.Where(x => x.Position == model.Position).FirstOrDefault();
model.Updateddate = Getadvert.LastUpdatedDate;
return Json(model, JsonRequestBehavior.AllowGet);
}
catch
{
return Json(new { success = false });
}
}
View
@Html.TextBoxFor(m => m.Updateddate, new { @id = "UpdatedDate" })
Script
function UpdateModal() {
var formdata = $('#Editform');
var data = formd.serialize();
$.ajax({
url: '@Url.Action("_Update", "Home")',
type: 'POST',
data: data,
success: function (data) {
if (data) {
var src = data.Updateddate;
var src = src.replace(/[^0-9 +]/g, '');
var dateupdated = new Date(parseInt(src));
$('#Updateddate').val(dateupdated);
}
else {
var message = data.message;
alert(message);
}
}
});
}
Upvotes: 1
Views: 1828
Reputation:
If you want it to be formatted as shown in the database, then it is easiest to format it on the server and send it as a string. In your JsonResult
, create an anonymous object containing only the properties you need in the view and return that, rather than your model
[HttpPost]
public JsonResult _Update(EmpViewModel model)
{
try
{
var Getadvert = context.Employee.Where(x => x.Position == model.Position).FirstOrDefault();
// format the date
string date = Getadvert.LastUpdatedDate.ToString("yyyy-MM-dd HH:mm:ss.fff")
return Json(new { success = true, date = date });
}
catch
{
return Json(new { success = false, message = "...." });
}
}
and then in the script
function UpdateModal() {
....
$.ajax({
....
success: function (data) {
if (data.success) {
$('#Updateddate').val(data.date);
}
else {
alert(data.message);
}
}
});
}
Upvotes: 1