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?
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())
From your model you should have the DateTime property.
public class YourModel {
public DateTime YourDateField { get; set; }
}
Then in your View
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).
如果您希望将DateTime
属性基本上转换为JS Date
,您可以尝试以下方法:
var jsDate = Date.parse('@Model.EndDate.ToUniversalTime().ToString("r")');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.