How to remove default date in mvc4 textbox? - c#

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

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

How to handle invalid date in mvc

I have a textbox for date of birth on the index page. I have to validate user to enter complete date format(mm/dd/yyyy), but its allowing to post 03/12(mm/dd) without year and in c# side it converted to 03/12/2015.
My requirement is to validate user to enter complete date format.
I used data annotation but that also not handling (mm/dd) as invalid date.
#Html.TextBoxFor(m => m.Search.DOB, new { #class = "form-control datepicker" })
Maybe you could use regular expression in javascript,
when fucusout event be triggered!
or solve the problem by following
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
public DateTime StartDate { get; set; }
You can use the html5 form validation it works without javascript.
For example:
<input type="text"
name="DOB"
placeholder="MM/dd/yyyy"
title="MM/dd/yyyy"
required
pattern="^([1-9]|1[0-2])/([1-9]|1[0-9]|2[0-9]|3[0-1])/\d{4}$" />

Time field receiving value from database, yet not showing

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

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.

auto-mapping of element in view to model from type dateTime

I have value of text box with some date time format (the default that DatePicker supplies - for example - 01/23/2014).
<input type="text" name="OrderDate" value="" id="OrderDate" class="datepicker field field119 datepicker-init" />
I have correlative Property in the model class with the same name and ID as the element in the view.
public DateTime OrderDate { get; set; }
at this point everything is matched and once submit I get the right value in my controller.
Now - I'd like to change the default DatePicker format -
for example:
$(".datepicker").datepicker({
minDate: 0,
dateFormat: 'dd/mm/yy'
});
and I fail to "explain" the model proprty how to serlizae the text box value - instead I get the default DateTime and not my time.
the question : how to change the text box date format that the DateTime property will know how to serialize that?
Ok, here is how you get this working.
Firstly jQuery UI formats the date you need using dd/mm/y, so you need to change your javascript to this:
$(".datepicker").datepicker({
minDate: 0,
dateFormat: 'dd/mm/y'
});
See jsFiddle here:
http://jsfiddle.net/hutchonoid/Fa8Xx/1376/
Then you need to format the model date in the view, you can do this like so:
#Html.TextBoxFor(m => m.OrderDate, String.Format("{0:dd/M/yy}", Model.OrderDate),
new { #class = "datepicker field field119 datepicker-init" })
This works nicely with model binding to when posting the date back to the server.

Categories