Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Format of Hidden DateTime

I have a model with a DateTime property that in one place is placed in a hidden input field.

@Html.HiddenFor(m => m.StartDate)

Which generates the following HTML:

<input id="StartDate" name="StartDate" type="hidden" value="1/1/2011 12:00:00 AM" >

The problem is that the time is included in the value and my custom date validation expects a date in the format of ##/##/#### thus causing validation to fail. I can easily alter my custom date validation to make this situation work but I would rather make it so that the hidden field puts the value in the correct format.

I have tried using the DisplayFormat attribute on the model property but that doesn't seem to change the format of the hidden input.

I do realize that I could just create the hidden input manually and call StartDate.ToString("MM/dd/yyyy") for the value but I am also using this model in a dynamically generated list of items so the inputs are indexed and have ids like Collection[Some-Guid].StartDate which would make it a bit more difficult to figure out the id and name of the input.

Is there anyway to make the 'value' value come out in a specific format when rendering the field on the page as a hidden input?

like image 494
Nick Olsen Avatar asked Nov 29 '11 02:11

Nick Olsen


1 Answers

You could use a custom editor template:

public class MyViewModel
{
    [UIHint("MyHiddenDate")]
    public DateTime Date { get; set; }
}

and then define ~/Views/Shared/EditorTemplates/MyHiddenDate.cshtml:

@model DateTime
@Html.Hidden("", Model.ToString("dd/MM/yyyy"))

and finally in your view use the EditorFor helper:

@model MyViewModel
@Html.EditorFor(x => x.Date)

This will render the custom editor template for the Date property of the view model and consequently render the hidden field with a value using the desired format.

like image 154
Darin Dimitrov Avatar answered Oct 17 '22 13:10

Darin Dimitrov