ASP.NET MVC Format of Hidden DateTime

2019-04-28 13:18发布

问题:

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:

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.