MVC.NET milliseconds get lost when using Html.hidden on a DateTime LastUpdated column for version tracking

I think the problem is that writing out the last update time into a hidden field like that will just do a ToString on the date which by default won't render out the milliseconds. You could try rendering out the timestamp as some absolute value such as ticks:

<%= Html.Hidden("LastUpdate", Model.LastUpdate.Ticks) %>

You can then reconstruct your datetime on the other side by converting the value back into a long & reconstructing the DateTime:

var dt = new DateTime(Int64.Parse(ticks));

You won't belive me, but try this: Before the return on your controller, do a

ModelState.Remove("LastUpdate");
return View(model);

Reason, someone on infinite confidence decide Html.Hidden would keep "posted" values discarding modifications. Even when created on c# on the same page.

This simple way you delete it from the ModelState so it catches the new value instead of posted.

Some people says the default behaviour its right, but please, I was working with a hand-made grid with an integrated company search (company/products), and a hidden field for the key of the products(a long). Changing the company posted on the same page.

<%= Html.Hidden("detalleProductos[" + i + "].PRO_PRODUCTOEMPRESAID", item.PRO_PRODUCTOEMPRESAID)%>
<%= Html.Hidden("detalleProductos[" + i + "].DET_DETALLEENCUESTAID", item.DET_DETALLEENCUESTAID)%>

I spent so many hours trying to figure out WHY it updated the wrong company (the first I loaded). Because it remembered the first one and discarded the modification I made on c# on the same page. Hard to catch.

Finally I had to do this:

foreach (var s in ModelState.Keys.ToList())
                if (s.StartsWith("detalleProductos"))
                    ModelState.Remove(s);

I was so frustrated I decided to post my workaround...

Good luck!


If you don't want to use Ticks, TextBoxFor will work if you specify the date format and the html hidden attribute.

@Html.TextBoxFor(model => model.CreatedDate, "{0:dd/MM/yyyy HH:mm:ss.fff}", htmlAttributes: new { @type = "hidden" })