How can I format a DateTime in a Razor view? - asp.net-mvc

I have variables like:
DateTime crd = a.CreationDate; (shown as a variable in C# but available in razor views)
I want to show these as a date using the format: 11/06/2011 02:11
Ideally I would like to have some kind of HTML helper for this. Anyone out there already have something that might meet my needs?

You could create a Display Template or Editor Template like in this answer, but the format would apply to all DateTime variables in the given scope (maybe good or bad).
Using the DisplayFormat attribute works well to define formats for individual fields.
Remember to use #Html.DisplayFor(model=>model.crd) and/or #Html.EditorFor(model=>model.crd) syntax for either of the above.
You can always use the DateTime.ToString() method in your views as well for more ad hoc formatting.
#crd.ToString("MM/dd/yyyy HH:mm") // time using a 24-hour clock

in your model you can set [DisplayFormat] attribute with formatting as you wish
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
pubilc DateTime CreationDate{ get; set }

Use this code to format your date:
#string.Format("{0:ddd}",Convert.ToDateTime(Html.DisplayFor(model => model.Booking.BookingFromDate).ToString()))
If your date field with required attribute then you don't want to validate null value.
Other wise you can use ternary operator

How about
#crd.ToShortDateString()

Try Razor View
#Html.Raw(item.Today_Date.Date.ToString("dd.MM.yyyy"))

In the interest of completeness, you could also use string interpolation. I don't think this was an available feature when this question was asked.
#($"{crd:dd/mm/yyyy HH:mm}")
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

If you have a list of dates and want to grab the first:
Begin Date: #string.Format("{0:MM/dd/yyyy}", Convert.ToDateTime(Model.aList.Where(z => z.Counter == 1).Select(z => z.Begin_date).First()))

Related

How to extract only month, day and year portion of datetime from DateTime string?

I'm writing DateTime Formatter in ASP.NET MVC and need to format the datetime based on cultural info.
My model's property binds DateTime.Now volue to the view and as a result the view is displaying 3/21/2017 9:38:37 AM as a datetime.
I'm looking for the way to display 3/21/2017 or 21/3/2017 and etc based on the culture.
What is the best way to do it. I tried a few examples from
https://msdn.microsoft.com/en-us/library/5hh873ya(v=vs.90).aspx
<span>String.Format("{0:d}", #Model.ToString())</span>
But the view still display the full datetime value: 3/21/2017 9:38:37 AM
I know that might be easy question but anywhere need some input on that.
What is the best way to handle something like that?
C# has come helpers built into the DateTime class. You can do this to only get the date.
DateTime.Now.ToShortDateString();
Or using your code assuming mode is an instance of DateTime:
#Model.ToShortDateString()

Annotation Validation in Asp.net MVC just accept MM/dd/yyyy format

I have spent several hours reading a lot of articles, but I still cannot solve my issue.
I have a DateTime type property in my model:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public System.DateTime StartTime { get; set; }
I have set the format to dd/MM/yyyy, so I expect a date like 14/12/2014 to be accepted. However, the validation always fails with the message: The field StartTime must be a date. I tried to input 12/14/2014 and it's ok.
Following several articles I have read, I tried to edit the format in razor code like:
#Html.TextBoxFor(model => model.StartTime, "{0:dd/MM/yyyy}")
And try using EditorFor like ataravati said in the below answer:
#Html.EditorFor(model => model.StartTime)
Or, change the culture in web.config to a culture in which day goes before month like GB:
<system.web>
<globalization uiCulture="en" culture="en-GB"/>
</system.web>
But, none of them work for me.
I tried using just a text input and input the date manually (not using any control like jqueryUI). However the validation still not accept my manually input if it's in dd/MM/yyyy format.
Could anyone show me the issue or show me the way to figure it out what the issue is?
UPDATE:
For someone who may have the same issue as me.
Following the post that Stephen mentions below, we have to create a 'date' validation to overwrite the default one of annotation validation. The custom validate we create will allow the format we want.
However, after that, the posted data to controller may not contain that data (in my case all datetime value is set to default datetime). The reason is the culture setting doesn't accept your format. We can change the culture setting in web.config but i don't think it's the best way because it can impact other value type (currency, number....) in your project. In my way, i create a custom ModelBinder for binding Datetime in the right format (an example here: http://www.codeproject.com/Articles/605595/ASP-NET-MVC-Custom-Model-Binder).
The above solution looks complicated. It shouldn't be so just for passing validation but up to now, i don't find anything better. Because of that, if someone have better solution that let annotation validation validates datetime value in format correctly, please share it.
The ApplyFormatInEditMode option only works when you use #Html.EditorFor, not #Html.TextBoxFor. Change your razor code to this:
#Html.EditorFor(model => model.StartTime)
Actually one thing that has been a life saver for me is as follows, and you don't need any data annotations (unless you want them etc):
#Html.TextBoxFor(m => m.StartDate, new { #Value = Model.StartDate.ToString("dd-MMM-yyyy") })
The above format can of course be changed to whatever.
Of course a popular thing to do is add say a datepicker too. I am using jQuery UI datepicker for ease of use:
#Html.TextBoxFor(model => model.StartDate, new { #Value = Model.StartDate.ToString("dd-MMM-yyyy"), #class = "form-control datepicker" })
My view model class example is shown below for completeness:
[DisplayName("Start Date")]
[Required(ErrorMessage = "An start date must be supplied")]
public DateTime StartDate { get; set; }
Hope it helps.

How do I make Html.TextBoxFor DateTime accept user input of dd.MM.yy

I'm trying to make a page where the user can search for articles. There is an option to limit the search based on a FromDate and a ToDate. Both of these are DateTime.
The user is asked to enter the date on the form dd.MM.yyas this is normal in our country. I can see the date in the URL after submitting the form and it looks as I want it to. The problem however is that MVC3 assumes the format is MM.dd.yy. How can I change this?
Some code:
This is the Razor code I use
<div class="toDate" >
<label>til dato</label>
#Html.TextBoxFor(m => m.DateTo, new { placeholder = "dd.mm.yy" })
</div>
And in the model all I have is:
public DateTime DateTo { set; get; }
I have tried using EditorFor, but I lose my placeholder text.
In short: How do I make my MVC3 model accept a DateTime input from the user on the form dd.MM.yy
If my question isn't clear enough, let me know and I'll try to clarify.
EDIT:
It appears that I need some clarification, so I'll try to do that by making a scenario:
The user enters his search criteria. He sets a DateFrom and a DateTo in two text boxes.
The form is submitted and posted back to the server.
On the server the DateTime object is treated on the form MM.dd.yy. I wish for it to be interpreted as dd.MM.yy.
I hope that helps.
[DisplayFormat(DataFormatString = "{0:dd MM yy}")]
pubilc DateTime DateTo { get; set }
Try setting up a custom validation attribute where you validate the date format according to your liking.
Here's a nice tutorial for it: http://msdn.microsoft.com/en-us/gg618485 (It's not as difficulty as it might seem at first, and can be really helpful).
Alternatively just build a regex validation attribute with something like:
RegularExpression(#"[0-3][0-9]\.[0-1][0-9].[0-9][0-9]")]
Above regex isn't perfect, but serves as an example.
Edit: If 3nigma's solution works for you that is obviously highly preferable to mine. :)

ASP.NET MVC Editor Templates

I have a question about Editor Templates. For example I have a model with date field, product prize field and weight of product field. I have successfully created Editor Templates for DateTime and Decimal. I'm given to understand that when I use EditorFor for any field it takes template depending on a data type of the field.
So when I use: EditorFor(m=>m.DateOfBirth) which is DateTime format it looks for DateTime template in EditorTemplates folder and EditorFor(m=>m.ProductPrice) which is double it looks for Double template, etc.)
Question is how can I differ that I want to use one Decimal template with string format ##0.00 for (double)ProductPrize and another template with format ##0.0000 for (double)ProductWeight?
Any help would be appreciated
You may want to use an overload of EditorFor, which accepts template name as second parameter, like:
EditorFor(m=>m.ProductPrice, "PriceEditorTemplate")
More info: MSDN
Define it in your model using the UIHint attribute:
[UIHint("MySpecificEditorTemplate")]
public ProductPrice {get;set;}
And EditorFor will use the MySpecificEditorTemplate.cshtml for example.

Where is the best place to format Model properties in ASP.NET MVC(3)?

I've been looking a lot recently as best practices within the ASP.NET MVC framework, specifically around sparation of concern. My question here is, if I have a property on a model, where is the best place to do some formatting on that property?
I've thought about a few options but am not sure which is best. The example uses a DateTime. Sorry this got a bit long.
Option 1:
In the view: #Model.TheDate.String("{0:'blah'dd/MM/yyyy}")
I know this isn't right because the format string shouldn't be here (what if I want to change the format throughout the whole app)
Option 2:
Extension method used within the view: #Model.TheDate.DisplayItNicePlease()
This kind of makes sense because the view is chosing the extension method to use for formatting and the viewmodel just exposes the date property to the view. Not sure if the view or view model should be responsible for formatting though.
Option 3:
In an Html Helper method, i.e. something like Where should I place Declarative HTML helpers in ASP.NET MVC 3 so you could use:
#Html.DisplayDateNice(Model.TheDate)
Option 4:
Extra property on the view model to format it and return a string e.g.:
public string TheDateStr
{
get
{
return TheDate.DisplayItNicePlease();
}
}
And then in the view you just have
#Model.TheDateStr
Fairly similar to option 3 only it keeps the view really, really simple - the view literally just outputs what is in the model and doesn't care about the format of the data.
Option 5:
DisplayFormat attributes, e.g.:
On the view model:
[DisplayFormat(DataFormatString = "{0:'blah'dd/MM/yyyy}")]
public DateTime TheDate { get; set; }
And then on the view:
#Html.DisplayFor(m => m.TheDate)
I like this apart from again the format string is not reused, so bring on option 5...
Option 6:
Some kind of custom DisplayFormatAttribute e.g. NiceDateDisplayFormatAttribute.
This seems to me like it might be the nicest solution and works well if you just want a simple string formatting. I think this gets more complicated if you want something more complicated, e.g showing relative time (Calculate relative time in C#), in which case maybe this is best being in an extension method/html helper.
There are probably other ways I'm not even aware of...
Either use an extension helper to format the type if this type formatting will be used a lot or add an extra property in the Model to return a formatted version of the original property.
For a single view, I personally use option 5: putting it in the view model.
If date format's being used for multiple pages, you can create a html helper extension for formatting the date. So in the view, you'd have something like
#Model.TheDate.ToDateString()
But overall, i still prefer option5 because i create viewmodels for everypage, and just throw a DisplayFormat attribute on it.

Resources