1

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?

WeSt
  • 2,452
  • 4
  • 17
  • 34

2 Answers2

1

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?

Community
  • 1
  • 1
WeSt
  • 2,452
  • 4
  • 17
  • 34
  • I think it is correct answear. Thanks for explanation. By the way it could be better for programmers to pass those data (at least if not null) automatically :) – Sebastian Xawery Wiśniowiecki Jan 02 '15 at 14:40
  • 1
    This is simply not possible. HTML and HTTP was created way before Asp.NET MVC, so MVC can only play to the rules set by HTML and HTTP. The magic (that is parsing the HTTP POST on the server to a business object) is all MVC can do. Alternatively, you can extend the HTMLHelper and add a method which would do that for you (e.g. adding a Hidden field for each unused property in the Model). – WeSt Jan 02 '15 at 14:45
1

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)
JLRishe
  • 90,548
  • 14
  • 117
  • 150