8

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?

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm. The only downside is that I have to have a separate model for this instance when the field is hidden than when I actually need it to be editable. But, that really isn't a bad thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.