Reputation: 1843
In my Model I have some DateTime
variable that is not touched in View template, but set to DateTime.Now
in GET method before sending to View. When I displayed it in View it is OK (presenting actual Date and Time).
Rest of variables is changed in form's fields and then send with POST method to contoller's action.
When I set breakpoint in contoller's POST action then I see the value of the variable is set to {0001-01-01 00:00:00} even though I didn't change the value anywhere before.
So the question is: Is View reseting all values in its Model?
Upvotes: 1
Views: 53
Reputation: 101700
It sounds like your datetime is not included among the fields that are sent back to the server and it's therefore getting initialized with the DateTime
default value (0001-01-01
).
You need to roundtrip it back to your server if you want your POST handler to receive it:
@Html.HiddenFor(m => m.MyDate)
Upvotes: 1
Reputation: 2684
You have to look behind the scenes to see what is happening here. The GET
method returns the model with the variables set, which is transferred to the client. On a submit, the client takes all fields and sends them to the server, where it is parsed to the Model
again. Only the fields that are present as some HTML code (e.g. inputs) or set via JavaScript on the client are transferred. To keep the DateTime
value, you need to create a Hidden
field for it.
Html.HiddenFor(m => m.DateProperty)
See this question, which covers the same problem: What does HTML.HiddenFor do?
Upvotes: 1