0

In my model I'm storing the timestamp in milliseconds, like this:

public Nullable<long> timestamp { get; set; }

I want the users to add the date in text format (later I'll probably add a datetimepicker) and convert it to milliseconds.

This is what I have in my view

    <div class="form-group">
        @Html.LabelFor(model => model.timestamp, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.timestamp, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.timestamp, "", new { @class = "text-danger" })
        </div>
    </div>

This shows an edittext with an arrow for changing the integer values (1, 2, 3...) as my field type is long.

How can I allow the users to introduce a string instead of long, like "2015/11/11 18:14" and convert it to milliseconds automatically for storing in my timestamp long field?

nano
  • 2,511
  • 4
  • 25
  • 42
  • 1
    Doesn't [this](http://stackoverflow.com/q/17959440/1849444) helps you? – teo van kot Nov 11 '15 at 12:26
  • 1
    What about converting your timestamp field to nullable (datetime?) and letting user select the date using a datepicker? Then you should be able to convert your timestamp into millisecs just before storing it in the database. You can convert millisecs in to datetime just after retrieving it from the database too. – Kosala W Nov 11 '15 at 12:28

2 Answers2

1

This is what viewmodels are for. Make a viewmodel with all the same properties and timestamp as a datetime instead of a long. Bind that with your view. Then map it to your data model on retrieve or posts and convert the datetime to a number of milliseconds (and milliseconds to datetime) on the server.

mgiesa
  • 1,023
  • 7
  • 9
0

You can easily convert date in timestamp, like here i think that's not your problem.

A quick and dirty way to resolve your problem is replacing Html.EditorFor with Html.TextBox. A quite better way is customize the editor template like here.

The definitive solution is use the MVVM (Model-View-ViewModel) pattern, that consist in create a class, called ViewModel that is the model passed to the view that is different than Model. In controller you may manage the conversion between ViewModel and Model. I use automapper library to simplify conversions. Here an example

Community
  • 1
  • 1
fiorebat
  • 3,431
  • 2
  • 18
  • 18