Milliseconds are being truncated by an ASP.NET MVC Hidden Input element - asp.net

I have a View that renders a list of items, and each item contains a Date property.
<%:Html.HiddenFor(m => m.Items[j].Date)%>
A number of other properties are hidden or shown, and the user is able to enter comments against any item and save these comments to the database. It's a 'bulk edit' type View.
I've used these Views before to good effect, but I'm having a problem with the Date property because it renders thus
<input name="Items[3].Date" type="hidden" value="3/05/2012 11:56:48 AM" />
The problem is that I need to use the DateTime as a part of the primary key for this data item. I could truncate the milliseconds in the database to allow the match but there is no guarantee that there will only be one data point per second.
How do I ensure that the hidden input field for my DateTime retains all of the property's information, including the milliseconds component?

well do you really need to use
<%:Html.HiddenFor(m => m.Items[j].Date)%>
why not just keep it simple
<input type="hidden" name="Items[<%:j%>].Date" value="<%:model.Items[j].Date.ToString("dd/MM/yy/ HH:mm:ss.fffff")%>"/>

I've not had any success forcing the format of a DateTime in a HiddenFor field.
The DisplayFormat attribute can force the format for a DisplayFor field but has no effect on a HiddenFor field.
I resorted to the below no-quite-a-hack to get this to work - serialize and deserialize the ticks property to ensure the true time is retained.
public long DateTicks
{
get
{
return this.Date.HasValue ? this.Date.Value.Ticks : 0;
}
set
{
if (value == 0)
this.Date = null;
else
this.Date = new DateTime(value);
}
}

Use
<%:Html.HiddenFor(m => m.Items[j].Date.Ticks)%>

Use the DisplayFormat attribute on the Date property in your model, and spell out the milliseconds in the format string:
[DisplayFormat(DataFormatString = "{0:yyyyMMddhhmmssfff}")]

Related

How to force RFC3339 string for all datetime for queries upon display as API?

Using Cake 3.2.4
What am I getting now?
Whenever a query is executed and there is a datetime field, it will be displayed as RFC2822 string.
e.g. "2016-07-18T09:00:00+0800"
What do I want?
I want RFC 3339 string
e.g. "2016-07-18T09:00:00+08:00"
What did I try?
$paginationQuery->formatResults(function (\Cake\Datasource\ResultSetInterface $results) {
return $results->map(function ($row) {
$datetime = $row['start_date'];
$row['start_date'] = $datetime->format(\DateTime::RFC3339);
return $row;
});
});
I kinda forced the original datetime object to display as string.
Okay, so what's wrong?
I am unsure if it's wrong to do so. As you can see clearly, the original value for $row['start_date'] is actually a datetime object. Not a string.
Can I keep the value as datetime object but when it gets displayed as api, it uses the RFC3339 format?

ASP.NET MVC5 stores date in wrong format

last days I have a quite hard time to convince MVC5 project to work with dates as I would like to. After intensive googling I've tried numerous attepmts to make it work properly, but without success.
Here is the problem:
I need to display and edit dates on my webpage in format dd.MM.yyyy (i.e. 15.07.2015). For editing I also need to use jquery ui datepicker. The thing here is that I've been able to successfully set that datepicker to display date in requested format, also the jquery validation is now correctly validating the date in given format. So as for UI so far so good. The problem appeared in moment, when I clicked submit button - there was an error message like:
The value '15.07.2015' is not valid for Start Date.
After brief investigation I've found that when the date is passed to server it has switched format - instead of dd.MM.yyyy the date is treated like MM.dd.yyyy. In other words the error pops up only when the day part of date is higher than 12.
Here are some highlights from my code:
In my model for date I have this:
[Required]
[Display(Name = "Start Date")]
[DataType(DataType.Date)]
[UIHint("Date")]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateStarts;
Which I believe is everything I need to do to make that date display in specified format and also force users to fill the textbox with date in right format.
As given in [UIHint("Date")], I have my own template for rendering textbox for editing date. The implementation of that template is following:
#model Nullable<DateTime>
#{
DateTime dt = DateTime.Now;
if (Model != null)
{
dt = (System.DateTime)Model;
}
#Html.TextBox("", dt.ToString("dd.MM.yyyy"), new { #class = "form-control datecontrol", type = "text", data_val_date = "Field must have format dd.MM.yyyy" })
<i class="fa fa-calendar form-control-feedback lowerzindex"></i>
}
The jquery datepicker has following implementation:
$('.datecontrol').datepicker({
onClose: function () { $(this).valid(); },
minDate: "-1M",
dateFormat: "dd.mm.yy",
});
So even the datepicker knows how the format should look like.
The last component is the validation by jquery.validation:
$.validator.addMethod(
'date',
function (value, element, params) {
if (this.optional(element)) {
return true;
};
var result = false;
try {
$.datepicker.parseDate('dd.mm.yy', value);
result = true;
} catch (err) {
result = false;
}
return result;
},
''
);
I know that the date is passed to server in some culture neutral format, but I thought that when I decorated code on numerous places with the requested format, this will ensure that the conversion into that culture neutral format will be done right. Or am I missing something else ?
Thanks
Your problem lies in the fact that you have not set proper Culture for your application. Your request end-up executing under culture that has month-day-year order (probably under en-US) causing you a problem.
The easiest solution is to set set the culture that actually has day-month-year order and . as date separator in your web.config, for example:
<configuration>
<system.web>
<globalization uiCulture="de-DE" culture="de-DE" />
...
https://msdn.microsoft.com/en-us/library/bz9tc508%28v=vs.140%29.aspx
The MVC uses current culture when parsing and binding posted data to your models/parameters.
It is advised to use same date separator across entire scope - html, client, javascript, server culture, ...

DisplayFormat in MVC datetime [duplicate]

This question already has answers here:
Format datetime in asp.net mvc 4
(3 answers)
Closed 8 years ago.
I am trying to format date time attribute in MVC 4 class like this :
[Required]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DateOfBirth { get; set; }
but not work DateOfBirth attribute accept date format month before day (EX:accept 1/27/1990 and not accept 27/1/1990)
I am searching for answers and trying many solution but not work like
enter link description here
using html helper:
#Html.TextBoxFor(Model => Model.DateOfBirth)
I appreciate any help thanks
The [[DisplayFormat] attribute is only for how to display the value in the view. It has nothing to do with the format that will be accepted. You can write some code to accept a string and in the server parse that back into a proper DateTime property. Store your DateTime, then when you go to display it back to the user you use your [[DisplayFormat] attribute
what you would do is use Regular Expressions to verify the user inputed a number then "/" then number then "/" then number.
Obivously you are not the first one to run into something like this , this is why datepickers are so commnly used , they force the user to pick a date and format it appropiatly
If your using #Html.TextBoxFor() to render the control, then [DataType(DataType.Date)] and ApplyFormatInEditMode = true in the [DisplayFormat] attribute is not really necessary. These are only applicable when you use #Html.EditorFor() to render the browsers date picker, in which case the format must be "yyyy-MM-dd" in order to display correctly in all browsers.
If you want to display the formatted date in a textbox, use
#Html.TextBoxFor(Model => Model.DateOfBirth, "{0:dd/MM/yyyy}")
Note if you post back "27/1/1990" (27th January 1990) and the current culture of the server has the date format "MM/dd/yyyy" then you will need a custom model binder to correctly bind the date. Refer example here

validation for Time HH:MM am or pm Format using regular expression

I am working on web application using asp.net with vb code.
I have a textbox for time field for which i am using regular expression validator.
the format i want is HH:MM am. the regular expression i am using is "(0[1-9]|[1][0-2])[:]" + "(0[0-9]|[1-5][0-9])[ ][A|a|P|p][M|m]"
i am entering the time example: 08:30 AM or 08:30 PM but the regular expression is showing error message.
Can anyone help me with correct regular expression.
thankyou all in advance
shubha
Use RegularExpressionValidator and below ValidationExpression. I have used that.
ValidationExpression="^(1[0-2]|0[1-9]):[0-5][0-9]\040(AM|am|PM|pm)$"
You don't need to use regular expressions, use DateTime.TryParse or DateTime.TryParseExact instead. I recommend using the regular TryParse method because it affords your visitors flexibility in their formats (e.g. some visitors might want to use the 24-hour system, whereas others can use the 12-hour system).
String input;
DateTime dt;
if( !DateTime.TryParse( input, CultureInfo.InvariantCulture /* change if appropriate */, DateTimeStyles.None, out dt ) ) {
// show error message
}
Now as you're using a validator, you'll want to wrap up this logic in a Validator subclass, but it's really easy:
public class DateTimeValidator : BaseValidator {
protected override bool EvaluateIsValid() {
String controlValidationValue = base.GetControlValidationValue(base.ControlToValidate);
if( String.IsNullOrEmpty( controlValidationValue ) ) return true;
DateTime dt;
return DateTime.TryParse( input, CultureInfo.InvariantCulture /* change if appropriate */, DateTimeStyles.None, out dt );
}
}
Then (assuming you've registered a tag-prefix in web.config) all you need to do is this:
<label>
Enter a valid date/time value.
<input type="text" runat="server" id="someDate" />
<myprefix:DateTimeValidator runat="server" controlToValidate="someDate" />
</label>
You will need a separate <asp:RequiredFieldValidator> if you want the field to be required.

How to display Date in dd/MM/yyyy format in the View in Asp.net MVC3

Controller's Code
int No= Convert.ToInt32(reqCookies["NO"].ToString());
Student stud = db.Students.Single(n => n.No == No);
return View(stud);
Im passing the No after the user logs In and want the record of that logged In person to be displayed which i have successfully done.My issue is again with the Date.When the record of the Logged In user is displayed the Date of birth is displayed along with the time.Like this 2/19/2001 12:00:00 AM, instead i only want the date part and not time something like this 19/2/2001.
To achieve this i have tried to convert the date in dd/MM/yyyy format
DateTime DOB=stud.DOB.tostring("dd/MM/yyyy");
Getting Error:No Overload for method 'ToString()' takes 1 Argument
Code in my View is like this:
<td>#Html.DisplayFor(model => model.DOB.ToString())</td>
And when i try to change the format in the View
<td>#Html.DisplayFor(model => model.DOB.ToString("dd/MM/yyyy"))</td>
Getting Error:No Overload for method 'ToString()' takes 1 Argument
Where can i make the conversion and how to truncate the time Part from getting displayed.
You could use DisplayFormat in the model to format your date:
[DisplayFormat(DataFormatString = "{0:dd/mm/yyyy}")]
public DateTime myDate { get; set; }
And then in the view:
<td>#Html.DisplayFor(model => model.DOB)</td>
Update:
Alternatively, since the DisplayFor() will simply output the date without any tags, you could just display the date without the use of templated helpers:
#Model.myDate.ToString("dd/MM/yyyy")
Or to display in a textbox you could use:
#Html.TextBox("Date", Model.myDate.ToString("dd/MM/yyyy"))

Resources