Time field receiving value from database, yet not showing - c#

A form I'm working on uses DateTime values to represent a time property (TimeStart). I've got a viewmodel (CourseSectionSessionViewModel) with a corresponding editor template.
The viewmodel:
public class CourseSectionSessionViewModel
{
[Display(Name = "Start Time")]
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:hh:mm tt}", ApplyFormatInEditMode = true)]
public DateTime TimeStart { get; set; }
}
The editor template:
<tr>
<td>#Html.EditorFor(model => model.TimeStart, new { htmlAttributes = new { #class = "form-control", #data_val = "false" } })</td>
</tr>
Both above have extraneous items excluded for brevity.
This results in the following image, which shows the fields, and the inspector indicates the fields have been populated (and debugging with Visual Studio confirms the actual data are coming from the DB), yet the visual looks like a default value.
The actual value seems to be getting added to the form field, yet the field is not evidently showing the value. Any suggestions?

The format is 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS' where HH is 00-23, mm is 00-59, ss is 00-59
Don't Pass 10:30 AM. Instead Pass value as 10:30 only

Related

Nullable Datetime in .NET CORE MVC

I have a view which is used for "Create" and "Update" a database model. The database model has a property which is a DateTime? (nullable). Now I am trying to use this nullable datetime in an ASP.NET Core MVC view which looks like the following:
#Html.TextBoxFor(model => model.MyNullableDate,"{0:dd.MM.yyyy}", new { placeholder = "dd.MM.yyyy", #class = "form-control form-control-sm", type = "date" })
This works very well for the "Create" process. If a date is set, it is written correctly into the database. But now I want to update the already existing database value model.MyNullableDate.
I read the value from the database and pass the value again to the view. The property MyNullableDate is set correctly and I saw in the debugger that the correct date is written into it.
But in the view, nothing is shown... it's only an empty textbox without the passed in value of MyNullableDate.
The property looks like this:
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
[DataType(DataType.Date)]
public DateTime? MyNullableDate{ get; set; }
What am I doing wrong? How can I show the value of MyNullableDate in the TextBoxFor?
This is related to the date format rather than the nullability.
See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date
The displayed date format will differ from the actual value — the
displayed date is formatted based on the locale of the user's browser,
but the parsed value is always formatted yyyy-mm-dd.
When I passed the format as below, the date displayed :)
#Html.TextBoxFor(
expression: model => model.MyNullableDate,
format: "{0:yyyy-MM-dd}",
htmlAttributes: new
{
placeholder = "dd.MM.yyyy",
#class = "form-control form-control-sm",
type = "date"
})

Why storing the date like dd-MMM-yyyy is getting converted to dd-MM-yyyy?

I have a very different kind of problem.
I have deployed my mvc application to live server.
It has date time format like this '01/07/2019'.
I have a textbox which is populated from jquery datetimepicker. It populates like this 27/Jul/2019 but in sql table it stores like 2019-07-17 00:00:00.000
and after binding the data from database to textboxfor, it appears like this 27-07-2019.
And upon saving it throws error for all the dates that are greater than 12 as a day e.g. 13/07/2019 but for 13/Jul/2019 it works good.
how to tackle this?
#Html.EditorFor(model => model.InspectionReport.InspectionDate, new { htmlAttributes = new { #class = "form-control input-sm pull-right text-box single-line" } })
jquery:
$("#InspectionReport_InspectionDate").datepicker({ dateFormat: 'dd/M/yy' });
class:
[Required]
[Display(Name = "Inspection Date")]
[DisplayFormat(DataFormatString = "{0: dd-MMM-yyyy}")]
public DateTime InspectionDate { get; set; }
In a date field of data type DateTime(2), a date value is stored as a value with no format.
Thus, to display the value, apply the format you wish, or a default format will be applied.
Try this,
#Html.TextBoxFor(model => model.InspectionReport.InspectionDate, "{0:dd-MMM-yyyy}", htmlAttributes: new { #type="date" })

conversion of a datetime2 data type to a datetime data type exception with dates after 1753/1/1

I have added a property to my Customer Model, created a migration and updated the database. The field created in DB is datetime.
here is my Model code
public DateTime BirthDate { get; set; }
here is the view that is actually a form where I insert date and other fields and submit the form.
<div class="form-group">
#Html.LabelFor(m => m.Customer.BirthDate)
#Html.TextBoxFor(m => m.Customer.BirthDate, "{0: dd-MM-yyyy}", new { #class = "form-control" })
</div>
and here is the Action in the controller
public ActionResult Save(Customer customer)
{
if (customer.Id == 0)
{
_context.Customers.Add(customer);
}
else
{
var customerInDb = _context.Customers.Single(c => c.Id == customer.Id);
customerInDb = customer;
}
_context.SaveChanges();
return RedirectToAction("Index", "Customers");
}
I have papulated the BirthDate field with 23/04/1976 and debug the application and check the value of customer.BirthDate which is 23/04/1976 12:00:00 AM. The date is note before 1753/1/1 but I m receiving the said exception.
I have also tried the following:
Make the field nullable by
public DateTime? BirthDate { get; set; }
the exception is gone but the date is not being saved to the database.
Removed the formate "{0: dd-MM-yyy}" from the view but in vain.
Inserted dates in different formats e.g. 23-Apr-1952, 1985-12-01 and 1987/1/2 but didn't work.
Visual Studio 2013 and Database is LocalDb of visual studio.
The fact that the error goes away by making the property nullable gives the answer. If a value was being set, then you would get exactly the same error as when the field was not nullable.
Therefore, the value is not being set, which stores a null if the field is nullable (confirmed by you saying it doesn't store the value - it's storing null).
So for a not-nullable property, when it isn't set, it will have the default value for a dot net DateTime, which is DateTime.MinValue, which would be valid if stored in an SQL server datetime2 but not in a datetime, where you get the 1753 error.
By the way, I'm assuming this LocalDb is basically SQL server, based on the 1753 error. For the record, in SQL server you should be using datetime2: DateTime2 vs DateTime in SQL Server
But this field is actually a Date, so you should be using the date SQL type.
So in summary, I suspect the BirthDate value in the Customer passed to the Save method has the value DateTime.MinValue. Now you need to work out why... (but that's a different question)
P.S. Are you using dd-MM-yyy on purpose? Should there be an extra y?
The actual problem lies in both DateTime viewmodel property and this TextBoxFor helper:
#Html.TextBoxFor(m => m.Customer.BirthDate, "{0: dd-MM-yyy}", new { #class = "form-control" })
Depending on current culture setting, this will generate plain input with specified date format which may not matched with current culture setting in server, which causing default model binder to ignore its value and uses DateTime.MinValue as default value (because it's not a nullable type), which doesn't fit for datetime column type in SQL that has minimum value of 1753-01-01 (the equivalent type of System.DateTime in T-SQL is datetime2).
The most recommended setup to create input helper for DateTime property is using DataTypeAttribute set to DataType.Date and DisplayFormatAttribute to specify the format string:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime BirthDate { get; set; }
Then, use either EditorFor or TextBoxFor with type="date" attribute to generate date input:
#* TextBoxFor *#
#Html.TextBoxFor(model => model.Customer.BirthDate, new { #class = "form-control", type = "date" })
#* EditorFor *#
#Html.EditorFor(model => model.Customer.BirthDate, new { htmlAttributes = new { #class = "form-control" } })
Note: The same setup like above also apply for Nullable<DateTime>/DateTime? property.
Additionally you should check for IsValid property of ModelState before using SaveChanges() and return the same view when validation failed:
[HttpPost]
public ActionResult Save(Customer customer)
{
if (ModelState.IsValid)
{
if (customer.Id == 0)
{
_context.Customers.Add(customer);
}
else
{
var customerInDb = _context.Customers.Single(c => c.Id == customer.Id);
customerInDb = customer;
}
_context.SaveChanges();
return RedirectToAction("Index", "Customers");
}
else
{
// validation failed, show the form again with validation errors
return View(customer);
}
}
Related issue: ASP.NET MVC date not saving when posting

How to remove default date in mvc4 textbox?

I have one Textbox in mvc4 application as below.
#Html.TextBoxFor(x=>x.dateofAction, ViewBag.filterdateTime as string, new { #id = "dateofAction", #placeholder = "Date Of Action", #class = "txtBox form-control calender validate[required]" })
I am using jquery calender for this textbox.
$(document).on('focus', '.calender', function(){
$(this).datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
showOn: 'button',
buttonImage: '/images/icondate.png',
buttonImageOnly: true
})
});
This is my model
[DisplayName("dateofAction")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime dateofAction { get; set; }
I am facing problem when first time page loads default date 1/1/0001 12:00:00 AM is displaying in textbox. Actually i want to show placeholder value.
May i know why i am not able to get placeholder value?
In order to display an empty textbox with the placeholder, you need to make your property nullable. If also want a date to be selected, then you can also decorate the property with the [Required] attribute.
Note also that your [DisplayFormat] is unnecessary and is ignoted by the TextBoxFor() method. You should also be using the [Display] attribute, not [DisplayName] Your property should be
[Display(Name= "Date of Action")]
[Required(ErrorMessage = "Please select a date")]
public DateTime? dateofAction { get; set; }
Then in the view your code should be just
#Html.TextBoxFor(x=>x.dateofAction, new { #placeholder = "Date Of Action", #class = "txtBox form-control calender validate[required]" })
and your datepicker plugin should be initialize when the DOM is rendered, not each time its focused
$('#dateofAction').datepicker({
dateFormat: "dd/mm/yy",
....
})
the DateTime is struct and value. when you pass model to view "dateofAction" has default value. two way for this challenge:
make dateofAction as nullable.
set dateofAction to DateTime.Now when create model.
Two ways to solve this problem.
set the entity Nullable by adding "?" next to the datatype of entity
like public DateTime? dateofAction { get; set; }
If you don't want to make the entity Nullable the you can add this code in the view "view.cshtml"
var variableName =
Model.Value.ToString("d") == default(DateTime).ToString("d") ? "" :
Model.Value.ToString("d");
in this case Model.Value.ToString("d"); is replaced by Model.dateofAction.ToString("d");
Use "variableName" this as value in your input field
in ToString("d"), "d" is string formatter
Learn more about string formatting here

Override default date of JqueryUi datepicker

I have a datepicker on a page as
#Html.TextBoxFor(m => m.ProposedLaunchDate, new { #class = "dateselector", #style = "float:left;" })
(This is using the Javascripts from JQueryui.com)
In my model the variable to hold the date is a string (for specific reasons), as
public string ProposedLaunchDate { get; set; }
On saving I can save my selected date well.
However on redisplaying , in the model I get the value I saved,but on the form the date-picker is taking today's date (and not displaying the value in my model)
Why so ?
How can I correct this ?
By default, jQuery datepicker will show currentDate as selected. Inorder to set our custom date to datepicker, you have use the option called setDate provided by datepicker.
$(".dateselector").datepicker('setDate', '04/11/2014');
|
Make sure about the dateFormat__________|

Categories