ASP.NET MVC Hidden Date Format

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

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

What 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 check expects a date in the format ## / ## / ####, which will cause the check to fail. I can easily change my custom date check so that this situation works, but I would rather have the hidden field put the value in the correct format.

I tried using the DisplayFormat attribute for the model property, but didn't seem to change the format of the hidden input.

I understand that I can simply create hidden input manually and call StartDate.ToString ("MM / dd / yyyy") for the value, but I also use this model in a dynamically generated list of items, so the inputs are indexed and have identifiers such as Collection [ Some-Guid] .StartDate, which makes it difficult to determine the identifier and input name.

In any case, so that the value "value" appears in a certain format when rendering a field on a page as a hidden input?

+6
source share
1 answer

You can use your own 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 :

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

This will create a custom editor template for the Date property of the view model and therefore display a hidden field with the value in the desired format.

+9
source

Source: https://habr.com/ru/post/902608/


All Articles