I want to create a simple ASP.Net form, that will get birth dates.
I have a model with this property:
[DataType(DataType.Date)]
public DateTime? BirthDate{ get; set; }
and in my view (is using the datepicker):
#Html.LabelFor(model => model.BirthDate)
#Html.TextBoxFor(model => model.BirthDate, new { #class = "form-control date-picker" })
#Html.ValidationMessageFor(model => model.BirthDate, "", new { #class = "text-danger" })
The only one setting on my javascript datepicker is:
format: 'L'
because I want show dates without times.
Now, I can't save, because of the validation error:
The value '12/23/2000' is not valid for BirthDate.
Now, I KNOW, its a globalization error... I need set culture in <globalization> element in web.config, etc...
But, have you noticed I set no formats (except the datepicker format "L")? I want that form get birthdates from people in any country, no a specific culture/format etc.
Is this possible? How can I do it?
Edit:
which date picker are u using?
The JQuery one, but this is not a requeriment, I can change to any datepicker that can easily handle different save formats "yyyy-mm-dd" and display format.
Which locale your server is located and which format do you prefer to work within your MVC code and to persist in database?
I dont know where my customer will host the site, its AWS... I prefer work with en-us.
Assuming that your datepicker can return the selected date in Date() js object. I would suggest to convert the date value in to a standard format like ISO8601. So what you have to do is to attach a onChange event on your date picker and convert the selected Date() value into ISO8601 format. You may assign this converted value to a hidden field (simply date.toISOString()).
MVC .net parser also understand ISO8601 format so when your form data is posted on server it is parsed to correct date value. See this question also.
I have create a jsfiddle using jquery UI datepicker. It uses a altFormat and altField which can be used for internal date format irrespective of whatever date format is shown to user in actual date input field.
Find the jsfiddle here - https://jsfiddle.net/Prasoon1983/kyjvwkLd/2/
$("#dob").datepicker({
altFormat: "yy-mm-dd",
altfield:"#dobInternal"
});
$( "#dob" ).datepicker( "option", "altField", "#dobInternal" );
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<input type="text" id="dob" />
<input type="text" id="dobInternal" />
I have used an input control for display purpose but you can use a hidden input.
Hope it helps.
Make your property as below
[RegularExpression(#"(\d{2}|\d{1})[/](\d{2}|\d{1})[/]\d{4}",ErrorMessage ="Birthday field must be ad dd/mm/yyyy format.")]
public DateTime? BirthDate{ get; set; }
Above regex only for dd/mm/yyyy format.If you need alternatives you must add that sign in [/].
Type of birthdate property of ViewModel can be string now.You can convert it to DateTime when you need
Globalization is really hard. But if you relaying on Javascrip then you can display selected date in one format and send it to server using different one e.g. ISO standard.
On server side I would prepare strict validator - e.g. accept only date in ISO format. When you receive request with some strange input then respond with error (with proper message).
Related
I have a 'date' type input, and I'm trying to get the Razor code to pre-fill the date with information that the server already has, because it's for an Edit field on an MVC ASP.NET Core app I'm working on.
The code I'm using is:
<input type="date" name="DeliveredDate" id="DeliveredDate" value='#Model["order"].DeliveredDate.ToString("mm/dd/yyyy")'>
I can get the code to show the string in any other part of the page, but is there a trick to getting that same string to populate the value of a date field? All my googling hasn't turned up anything particularly helpful.
You can use either #Html.TextBox() or strongly-typed #Html.TextBoxFor() helper to do so, by either setting DisplayFormatAttribute or date format directly in the helper:
Viewmodel property
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DeliveredDate { get; set; }
View
#Html.TextBox("DeliveredDate", Model["order"].DeliveredDate, "{0:MM/dd/yyyy}", new { type = "date" })
#Html.TextBoxFor(model => model.DeliveredDate, "{0:MM/dd/yyyy}", new { type = "date" })
Or using EditorFor by setting date format, which automatically appends type = "date" attribute:
#Html.EditorFor(model => model.DeliveredDate)
If you're using tag helper, just set asp-for attribute:
<input asp-for="DeliveredDate" type="date" />
Notes:
1) Make sure that you're already set the date value inside controller action, e.g. model.DeliveredDate = DateTime.Now (model has type of Model["order"]).
2) The latter approach requires setting DisplayFormatAttribute in viewmodel property because there's no string formatting parameter to set the format from EditorFor or tag helper itself.
The correct command ended up being
#Model["order"].DeliveredDate.ToString("yyyy-MM-dd")
but then I learned from my instructor that there's a date range that is able to be displayed, and it varies with different platforms, but I'm pretty sure the range that can be displayed is between the years 1950, and 2049.
Once I actually set the dates it was supposed to display to one that was within that range, it worked, and if I tried to display a date outside of that range, it would break again.
I've got an ASP.NET MVC 5 application. Date fields are prolific. Things are working and behaving propertly, however the W3C Markup Validator complains about the date text fields having an improper type attribute value.
I'm rendering the input's for DateTime or nullable DateTime properties using the EditorFor helper:
#Html.EditorFor(model => model.BeginDate)
This is getting translated to:
<input type="datetime">
The "datetime" value of the type attribute is no longer a standard according to the W3C HTML5 Forms standard. The supported date/time types are:
date - A date (year, month, day) with no time zone
time - A time (hour, minute, seconds, fractional seconds) with no time zone
I don't really want to create a custom Editor Template, because the standard MVC editor template works perfectly, except the type="datetime" attribute value is non-standard.
How can I override the default behavior of the EditorFor method for DateTime objects so it creates <input type="date"> elements without creating my own Editor Template?
Annotate your model field with the DataType attribute
public class Model1
{
[DataType(DataType.Date)]
public DateTime BegineDate { get; set; }
}
I get a DateTime in SQL Server DataBase and want to display it in Input:
<input class="form-control" type="date" name="ExpireDate" id="expiredate" runat="server" value="31/12/2016" style="height: 30px; width: 267px">
and here is my C# codes:
Medicine med = new Medicine();
int a = GridView1.SelectedIndex;
med.ID = int.Parse(GridView1.DataKeys[a].Value.ToString());
DataProcess bal = new DataProcess(); DataTable dt = bal.getInfo(med)
expiredate.Value = Convert.ToDateTime(dt.Rows[0][5]).ToString("dd/MM/yyyy");
I put a break point just after the last line , I saw dt.Rows[0][5] got "{2017/5/31 0:00:00}" and expiredate.Value got "31/05/2017",but it just shows nothing without error in webpage. And this DateTime record is inserted into DataBase through exactly the same Input, I just don't know how to display it in the same Input when I pull it out from DataBase.
First time to ask, many thanks!
The problem here is the format of html date input and asp.net DateTime doesn't match. Html date input displays mm/dd/yyyy but the format behind is yyyy-MM-dd.
Try using expiredate.Value = Convert.ToDateTime(dt.Rows[0][5]).ToString("yyyy-MM-dd");
Hope this helps.
It seems that you are pushing a date inside a input field which is date type. But this won't work. Because html do not support the default value for raw date format. So you have to customize the date field using a javascript. However if ou take any help from Razor Html helper then you would be able to do this either not as you are on .NET framwork. Easily you can take help from previous answers jQuerydatepicker, here you can set a default date through javascript, which will show on your input field.
I would like to display only the date on the page.
SQL column has type date.
Model
public System.DateTime EndDate { get; set; }
View
#Html.DisplayFor(modelItem => item.EndDate.Date)
This gives me no warnings or errors, however the time is still displaying on the page.
DateTime.Date returns a new instance of DateTime with the time component set to midnight (rather than removing the Time completely), it's only useful for normalizing date/time values and is not intended for display purposes.
Anyway, you don't need DisplayFor, you can render the date directly:
#item.EndDate.ToString("yyyy-MM-dd")
You can use theDate.ToShortDateString() or use a custom date/time string format.
The benefit of ToShortDateString() is that it is CULTURALLY SENSITIVE making your application more accessible.
If you want to use the Html.DisplayFor template helper then you may want to build a ShortDateTime.cshtml display template. Learn more about that here:
https://stackoverflow.com/a/6001836/941058
Try the ToString() date formatters:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Example:
#Html.DisplayFor(modelItem => item.EndDate.Date.ToString("MMMM dd, yyyy")
I am having the following Razor Code to Render TextBox for ValidFrom Property of DateTime type.
#Html.TextBox("ValidFrom", (Model.ValidFrom.ToString("dd-MMM-yyyy")), new { #class = "FrmTextBox" })
And the same is rendering the Default Date(01-01-0001 00:00:00) as '01-Jan-0001' while opening of my Form and my values are also getting stored into the database once I submitted the form.
But, If I try to update the ValidFrom Property of the Subjected Record from the Database then the Record returning as 02-10-2012 00:00:00 but the Date is being displayed in the 02/10/2012 00:00:00 format only.
How to format the above DateTime Value into 02-Oct-2012.?
Could anyone please help..
Thanks in Advance.
Try to use the following attribute in your model.
[DisplayFormat(ApplyFormatInEditMode = true,
DataFormatString = "specify_format_string_here")]
Then, on your view : #Html.EditorFor(m => m.ValidFrom). More about editor templates you can find for example here. For your requirements format string should be smth like this:
"{0:dd-MMMM-yyyy}"