I have my date data annotation as
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreatedOn { get; set; }
In my view:
#Html.DisplayFor(item=> item.CreatedOn)
But my date appears as just: 11 12 2017 in my view, insteaed of 11/12/2017. What ate my /'s? Anything I forgot to include?
In the format-string, wrap the / in single quotes, so your model should look something like this:
[DisplayFormat(DataFormatString = "{0:dd'/'MM'/'yyyy}")]
public DateTime CreatedOn { get; set; }
When rendered on the page, it uses the desired format.
The Documentation on DataFormatString has a remark about formatting of dates, but doesn't mention anything about this issue of formatting forward-slashes. Their proposed solution about setting HtmlEncode = true didn't work for me. I found the solution in the alternative suggestion on the answer for this similar question.
It seems everything boils down to Culture info. As it currently stands it doesn't seem like we can specify CultureInfo in DisplayFormat, so i ended up defining a reusable helper method:
public static string FormatDate(this IHtmlHelper helper, DateTime date)
{
var formattedDate = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", date);
return formattedDateWithTime;
}
and in my view:
#Html.FormatDate(Model.CreatedOn)
Related
Typically, when I use the [DisplayFormat(DataFormatString="{0:d}")] attribute with a DateTime property in my model, the DateTime values correctly show only the date part only.
However, because Edge (and only Edge) overrides the Bootstrap Datepicker to show its own Datepicker, I have to change my attributes to the following (showing one property in my model as an example):
[Required]
[Display(Name="Start Date")]
[DataType(DataType.Text)] // this is required to make Bootstrap
// datepicker work with Edge
[DisplayFormat(DataFormatString="{0:d}")] // this attribute is now ignored
public DateTime? SelectedStartDate { get; set; }
In other words, I have to declare the DateTime field as text, and so when my page is rendered, it looks like this.
When the user selects a date, the correct format is shown, so that part is nailed down.
<script>
$(function () {
var formatparam = {format:"mm/dd/yyyy", setDate: new Date(), autoclose: true };
$("#SelectedStartDate").datepicker(formatparam);
$("#SelectedEndDate").datepicker(formatparam);
});
</script>
Is there something I can declare in the model or in the script block so that the default value appears as Date only and not as DateTime?
Given that SelectedStartDate will be string
#string.Format("{0:d}", Model.SelectedStartDate)
I have gone through several paradigm shifts and refactoring. Thanks to #Steven Muecke for his suggestion.
In earlier iterations, I had tried #Html.TextBoxFor(m => m.SelectedStartDate) without success. What I didn't know was that I also needed to add the formatting string, so it looks like this:
#Html.TextBoxFor(m => m.SelectedStartDate, "{0:d}")
So my Model is cleaner:
[Required]
[Display(Name="Start Date")]
[DisplayFormat(DataFormatString="{0:d}")]
public DateTime? SelectedStartDate { get; set; }
The behavior is now what I need it to be: the default view is formatted as a Date only and not DateTime.
In my ASP.NET MVC 5 dwith EF 6 project, I have a database where datetime format is stored as string like "dd-MM-yyyy". User can change this format any time. User will use the given format in the date fields in the view. But when they will post that. Automatically it will bind as a DateTime for that property. I am statically handling it by the following code
[DataType(DataType.Time), DisplayFormat(DataFormatString = "{HH:mm}", ApplyFormatInEditMode = true)]
public DateTime? EndingTime { get; set; }
public string EndingTimeValue
{
get
{
return EndingTime.HasValue ? EndingTime.Value.ToString("HH:mm") : string.Empty;
}
set
{
EndingTime = DateTime.Parse(value);
}
}
but I know it's not a best way to do that. There may need a model binder or filter or any kind of custom attribute. I will be greatly helped if you give me a efficient solution with sample code. Thanks in advance.
NB: I am using razor view engine. and my solution consists of 7 projects. So there is no chance of using Session in model. Again I have a base repository class for using entity framework.
People usually store the datetime in the database as a datetime.
Then wherever you do a translation from datetime to string that datetime can be displayed in a format that depends on the culture of the viewer.
By doing this you can quickly make a page with datetime formats that will format the datetimes nicely wherever you are.
change the culture you pass to the toString and the format changes.
please see this MSDN page for more info about it.
edit: (see comments below)
anywhere on server:
string WhatYouWant = yourTime.ToCustomFormat()
and create an extension method for the datetime that gets the format out of the database and returns a string in the correct format.
public static class MyExtensions
{
public static string ToCustomFormat(this DateTime yourTime)
{
// Get the following var out of the database
String format = "MM/dd/yyyy hh:mm:sszzz";
// Converts the local DateTime to a string
// using the custom format string and display.
String result = yourTime.ToString(format);
return result;
}
}
This will allow you to call it anywhere anytime on your server. You can't access the method client side in javascript. I hope this helps.
(To be honest I'm a new developer too and still have a lot to learn ^^)
I have tried many options regarding this problem. Now what I am doing is created an action filter to catch all the DateTime and nullable DateTime Fields. Here I am providing the binder.
public class DateTimeBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
DateTime date;
var displayFormat = SmartSession.DateTimeFormat;
if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName,"Invalid Format");
}
return base.BindModel(controllerContext, bindingContext);
}
}
in views the code I am formatting the date using same date format.
I have an ASP.NET MVC application with a model with the following property:
[DisplayFormat(DataFormatString = "{0:N1}", ApplyFormatInEditMode = true)]
public List<decimal?> Scores { get; set; }
I was expecting it to be formatted with one decimal when printed like this:
#Html.EditorFor(p => p.ContainingModelList[i].Scores[j])
It is not. It shows two decimals no matter what. If I try to implement a dummy property like this, formatting works though:
[DisplayFormat(DataFormatString = "{0:N1}", ApplyFormatInEditMode = true)]
public decimal? Test { get; set; }
// Test is later initalized with 1.35443M and rendered as "1.4"
So... does the DisplayFormat attribute in combination with EditorFor not support lists? Any way to work around it?
edit: I meant EditorFor, but wrote DisplayFor
I have this code:
#Html.TextBoxFor(m => Model.MyDateTime)
MyDateTime - is DateTime object.
It shows correct date and time inside textbox: 09/10/2010 05:19:56 PM
But when I try to click submit button it shows that it is incorrect value. I use jquery.validate.unobtrusive.js file for validation.
The gist of the solution I pointed to in my comment is that you can use a specialized model for the view which contains a string representation instead of the DateTime type, which allows you to easily validate the value with RegularExpressionAttribute. When you receive this model on the server (as posted from the client), simply convert it to a corresponding database model.
public class ViewModel
{
[Required]
[RegularExpression("\d{2}-\d{2}-\d{4}\s\d{2}:\d{2}:\d{2}")]
public string MyDateTime { get; set; }
public Model ToPoco()
{
return new Model {
MyDateTime = DateTime.Parse(this.MyDateTime, "MM-dd-yyyy H:mm:ss")
};
}
}
public class Model
{
DateTime MyDateTime { get; set; }
}
data annotation will work for you!
You could use dataannotaion for validate yor model field properly. Using such annatation you could manualy prvide format of date in your annotation passing string pattern to it. And in that case it will perefectly working with default mvc validation.
I have a model with a DateTime propery:
[DisplayName("Updated")]
public DateTime lastUpdatedDate { get; set; }
At the moment, I think I am incorrectly handling the formatting of the datetime in the view.
<tr>
<td>#Html.LabelFor(m=>m.lastUpdatedDate)</td>
<td>#Html.Label(Model.lastUpdatedDate.ToLongDateString())</td>
</tr>
I am sure this is wrong. Firstly, should I do the formatting in the model, and return string (In the model used for displaying the date - the Update model needs the DateTime type for the control)? But it gets complicated - timezones. Should I manipulate the value of the date time (based on a timezone selection by the user on registration) in the model on the get; .. thing? (What's the called? The getter?? hehe).
Just trying to make my code friendly to work with, while I learn MVC.
If you want to elegantly deal with timezones, I suggest you read this answer. For simple formatting the DateTime property in your model, decorate it with the [DisplayFormat] attribute:
[DisplayName("Updated")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime lastUpdatedDate { get; set; }
and in your view:
#Html.DisplayFor(x => x.lastUpdatedDate)