C# MVC DateTime Picker Problems [duplicate] - c#

This question already has an answer here:
Default datetime picker in visual studio 2015 showing only date picker not allowing to select time
(1 answer)
Closed 6 years ago.
So. If I have this in my model :
[DataType(DataType.Date)]
public DateTime Birthday { get; set; }
I get a nice date picker field when I invoke (can't select time though) :
#Html.EditorFor(model => model.Birthday, new { htmlAttributes = new { #class = "form-control" } })
But, if I want to record something like date and starting time of an event :
[DataType(DataType.DateTime)]
public DateTime Start { get; set; }
I get just a regular text field.
Also, I've just noticed that when I want to edit existing record, date is empty and has to be entered again even though all other fields are populated nicely.

I think you can also specify the datetime-local property in HTML.
#Html.TextBoxFor(model => model.Property, new { htmlAttributes = new { #class = "form-control", #type="datetime-local" } })
This is a pretty simple and easy way to get a date/time picker in your application.
Edit:
To get date/time to be set as the "default", you need a bit of jQuery as this isn't possible through #Value (that I know of). I use the following to set the date/time on forms.
$(document).ready(function () {
var now = new Date();
var day = (#Model.myDate.Day.ToString().Length != 2) ? "0" + #Model.myDate.Day : #Model.myDate.Day;
var month = (#Model.myDate.Month.ToString().Length != 2) ? "0" + #Model.myDate.Month : #Model.myDate.Month;
var today = #Model.myDate.Year + "-" + (month) + "-" + (day);
$('#IdOfDateElement').val(today);
});

You can save date-time as string in db or manipulate datetime value posted from UI from. See reference :
http://eonasdan.github.io/bootstrap-datetimepicker/
http://forums.asp.net/t/1975676.aspx?Tutorial+for+Adding+Datepicker+in+MVC+5

Related

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" })

Get values to time span type using TimePicker and razor in ASP.NET MVC

I have a model that contains attribute of type TimeSpan:
public TimeSpan Time { get; set; }
I want the user to enter values using a form to get the time span. I'm using timepicker lib and razor #Html.EditorFor.
The problem is that the attribute Time always gets the default values. I searched for this problem and some people talked about changing the time format but I didn't know how to do it
The html looks like this
#Html.EditorFor(b => b.Time, new { htmlAttributes = new { #id = "time", #class = "form-control timepicker", #required = "" } })
when running the input looks like this:
html timepicker lib
How can I use the timepicker and razor in a simple way to get values for time span?

SQL Server 2012 Date datatype contains 12:00:00AM

I have a MVC CRUD site that has a Date Approved Textbox. When the new entry is created it is stored properly as "dd-MM-yyyy" in the SQL Sever. When I want to update an entry the Date Required textbox contains the date AND 12:00:00AM . I'm guessing this is because SQL Server is a date datatype and .Net is a DateTime. Any idea how to get rid of the 12:00:00AM ?
Failed attempts...
I've tried adding it to my viewmodel
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage="Required")]
[DataType(DataType.Date)]
[Display(Name="Date Requested")]
public DateTime? Date_Requested { get; set; }
and also...
string test = Convert.ToDateTime(model.Date_Requested).ToString;
EDIT
the html textbox
#Html.TextBoxFor(model => model.Date_Requested,new {#class="datepicker" })
EDIT JQuery DatePicker
$(".datepicker").datepicker({
onSelect: function () {
$(this).valid();
}
});
you could add another property, using ToShortDateString:
public string DateRequestedShortDate
{
get
{
return Date_Requested == null ? "" : Date_Requested.ToShortDateString();
}
}
or simply set the textbox value to the ShortDateString to keep your binding
TextBoxFor does not honor format attributes (not sure if this is intended or a bug). You can either use EditorFor:
#Html.EditorFor(model => model.Date_Requested,new {#class="datepicker" })
or set the format in TextBoxFor:
#Html.TextBoxFor(model => model.Date_Requested,
new {
#class="datepicker",
#Value = Model.Date_Requested.ToString("MM-dd-yyyy")
});
Expanding on Jonesy answer from above.
public string DateRequestedShortDate
{
get
{
return Date_Requested == null ? "" : Date.Parse(Date_Requested).ToShortDateString();
}
}
Parse won't mess up the data being inserted into SQL , hope it helps.

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__________|

MVC&EF: remove time from datetime

I have a model that contains a datetime field.
The column in the DB which it prepresents is of datatype 'date', so it has no time value.
The model date field is bound to a jquery-ui datepicker in my view.
When the page loads, it has time value: 1989/02/14 12:00:00 AM
How can I prevent the time value from being added?
Do I have to manually strip out the time portion with jQuery for every date field?
EDIT:
There is no point in editing the model, when the page loads its still there
Controller:
ClientModel c = DBContext.Clients.find(id);
//Doing any kind of date formatting here to c.DateOfBirth is ignored
return PartialView("_ClientDetailsView", c);
View:
#Html.TextBoxFor(model => model.DateOfBirth , new { #class = "date-field" })
I'm thinking that the solution would be something like a model attribute or a HtmlHelper parameter.
You can use the DataType attribute for this. Decorate your DateOfBirth property in the ClientModel with it:
public class ClientModel
{
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }
}
Also see the DataType enum.
You can also use the DisplayFormat attribute if you the DataType attribute doesn't fit your needs:
[DisplayFormat(DataFormatString = "dd MM, yyyy")]
public DateTime DateOfBirth { get; set; }
Thanks for the help Henk
In the end I grew tired of trying to find a 'proper' solution so I wrote the following jquery function and calling it on each page as required.
function DropTimeSegments() {
$(".datepicker").each(function (index, item) {
$(item).val(FormatDate(new Date($(item).val())));
});
function FormatDate(Date) {
return Date.getFullYear() + '-' + pad(Date.getMonth(), 2) + '-' + pad(Date.getDate(), 2);
}
function pad(num, size) {
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}

Categories