3

In Asp.Net MVC I have a model containing a property of type DateTime.

How can I access it in JavaScript?

Using @(Model.PrimitiveTypeProperty) works just fine, but not when it comes to a property of DateTime.

The problem is more complex, but I need to at least have an alter with this value.
Is it possible?

1
  • 1
    Are you just looking to display the date/time using JavaScript or do you need it as a javascript Date object?
    – James
    Commented Oct 3, 2012 at 10:50

3 Answers 3

3

You can put it in a hidden for example:

 @Html.HiddenFor(model => model.YourDate)

And then access it from javascript. After you modify it's value, on submit, you should get the value updated back to your controller.

And don't forget to put in in a form like:

@using (Html.BeginForm())
1
  • how do you modify it? I'm having trouble reading the data from it.
    – John Lord
    Commented Dec 28, 2018 at 22:43
2

From your model you should have the DateTime property.

public class YourModel {

   public DateTime YourDateField { get; set; }

}

Then in yourView you could do:

@Html.LabelFor(m => m.YourDateField);

Accessing it using JavaScript/jQuery:

$(document).ready(function() {
   var d = $("#YourDateField").val(); 
   alert(d);

  $("#YourDateField").val = "01/01/2000"; // sets the date which will then be posted back to the model on the form submit. 
});

This will alert the date value from your model.

 $("#YourDateField").val = "01/01/2000"; 

Changes the date client side. If yor View has a Form element, when it is submitted back to the server the value passed back will reflect the change (01/01/2000).

1

If you are looking to basically translate your DateTime property to a JS Date, you could try something like:

var jsDate = Date.parse('@Model.EndDate.ToUniversalTime().ToString("r")');
2
  • 1
    thanks, this is exactly want I intended...didn't work exactly like that, but it help to get it: var jsDate = new Date(parseInt(@(Model.EndDate.Year)), parseInt(@(Model.EndDate.Month)), parseInt(@(Model.EndDate.Day)));
    – Sandra S.
    Commented Oct 3, 2012 at 11:22
  • @SandraS. yeah the example I gave wasn't correct as Date in JS expects an epoch timestamp (which DateTime.Milliseconds wouldn't give). I have updated my answer with something less verbose than the one you are using. Also, with your one you will lose any time information associated with the date.
    – James
    Commented Oct 3, 2012 at 12:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.