Input with date format set from ViewModel and html class attribute
Asked Answered
H

2

5

I am working with razor view engine in asp.net mvc3.

Now, I need an input for a DateTime which should display the value in a fixed format (say dd-MMM-yyyy). So I can do:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MMM-yyyy}")]
public DateTime StartDate { get; set; }

And in the view:

@Html.EditorFor(model => model.StartDate)

But I need to add a class in the input. Which I think is not possible in EditorFor. So I could use

@Html.TextBoxFor(model => model.StartDate, new { @class = "Date" })

But the display format does not work in this case.

Model can be null. So,

@Html.TextBox("StartDate", string.Format("{0:dd-MMM-yyyy}", Model.StartDate))

will throw NullReferenceException.

Hypocycloid answered 11/11, 2011 at 3:25 Comment(2)
why the first one is not working to add class??? @Html.TextBoxFor(model => model.StartDate, new { @class = "Date" }) Can your date return a null value I think the exception is because your date may be nullInvoluntary
Thanks for the ApplyFormatInEditMode. I miss that parameter.Karrah
S
9

ophelia's way is a quicker version of mine. But this way is useful if you're going to have a few date fields in your application. So this is the way i like to do it:

-> In your solution explorer, create a folder inside Shared called "EditorTemplates"

-> In there, add a new (not strongly typed) Partial View. Call it "DateTime".

-> Open this view, and remove any code in there, and throw the following code in there:

@model System.DateTime
    @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date" /* + any other html attributes you want */ })

-> In your ViewModel, your date field should be like this:

[Display(Name = "My Date:"), DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime MyDate { get; set; }

-> In your main view, and any view you want to use a date field, you can just use EditorFor on the property, like so:

@Html.EditorFor(m => m.MyDate)

You can initialize the date field in your controller or set a default date in your viewmodel's constructor.

Sydelle answered 11/11, 2011 at 4:40 Comment(1)
Great answer, though you do not even need the DateTime EditorTemplate unless you are adding custom classes for DateTime EditorFor. You just need [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yy}")] in your ViewModel or Model and @Html.EditorFor(model => model.MyDateTime) will be formatted the way you defined it in the DisplayFormat attribute.Maciemaciel
C
2

I use this and its works fine:

    @Html.TextBox("ExpiryDate", String.Format("{0:ddd, dd MMM yyyy}", DateTime.Now), new { id = "expirydate" })

Hope this is what you mean/need :)

Cursor answered 11/11, 2011 at 4:5 Comment(1)
How would you format the date without using helpers? Such as: @Model.ExpiryDateMontenegro

© 2022 - 2024 — McMap. All rights reserved.