Model property formatting - c#

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)

Related

mvc view date display format

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)

How to declare date format style in model when `[DataType(DataType.Text)]` is used

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.

DataAnnotations.DisplayFormat doesn't seem to support lists. Any way to get around it?

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

MVC3 Date in UK Format not received on Controller

Given this VM
public class ApplicationDTO : BaseDTO
{
public DateTime Date { get; set; }
public int JobId {get;set;}
public int Status {get;set;}
[Required]
public string Message { get; set; }
public string ExpertCode { get; set; }
}
I have a hidden field thusly
#Html.Hidden("Date", DateTime.Now)
Which fiddler shows me is sent to the server as I would expect (UK format, I'm in the UK!)
But on the controller the date shows as being the default min. date
Is it just the UK format? If so, what is my best way round it? Whilst currently I am setting it to the current date, potentially it could be set to any given date i.e.
#Html.HiddenFor(x => x.Date)
I am using AJAX to submit the form, if that makes a difference.
If it is a Get MVC uses culture invariant format (Basically US format) by default during model binding. So it doesn't accept UK date format. I believe the design reasons are that a querystring could be passed around so therefore it needs to be culture invariant (I wasn't 100% convinced by that logic).
This article covers a possible solution http://xhalent.wordpress.com/2011/05/14/localization-of-dates-in-asp-net-mvc/
We just make sure we never do a Get with a UK date format
This questions also covers the issue Globalization problem with DateTime and ASP.NET MVC 3 Model Binding
you should use Data Annotation for Formatting the date on your Model or View model
public class ApplicationDTO : BaseDTO
{
[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}", ApplyFormatInEditMode=true)]
public DateTime Date { get; set; }
public int JobId {get;set;}
public int Status {get;set;}
[Required]
public string Message { get; set; }
public string ExpertCode { get; set; }
}
Apply the format according you.
As i have seen you are not providing any format to your property
I had a similar issue with dd.MM.yyyy format and had to set globalization element in web.config to appropriate culture and uiCulture attribute settings.
If you use #Html.Hidden (not the For helper) it won't be able to match the parameter in the request to the property in your model.
If you use #Html.HiddenFor(x=>x.Date, "28/2/2013") you will see the date populated appropriately.
Also you can verify the Request.Params collection. Put a break point in the Action. You'll see that one of the Params has your date.... JQuery does not affect this in any way.

How to validate DateTime inside TextBoxFor ASP.NET MVC

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.

Categories