简体   繁体   English

asp.net mvc 3访问javascript中的DateTime模型属性

[英]asp.net mvc 3 access DateTime model property in javascript

In Asp.Net MVC I have a model containing a property of type DateTime . 在Asp.Net MVC中,我有一个包含DateTime类型属性的模型。

How can I access it in JavaScript? 如何在JavaScript中访问它?

Using @(Model.PrimitiveTypeProperty) works just fine, but not when it comes to a property of DateTime . 使用@(Model.PrimitiveTypeProperty)工作得很好,但是当涉及到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. 然后从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. 从您的模型中,您应该具有DateTime属性。

public class YourModel {

   public DateTime YourDateField { get; set; }

}

Then in your View you could do: 然后在你的View你可以做到:

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

Accessing it using JavaScript/jQuery : 使用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). 如果yor View有一个Form元素,当它被提交回服务器时,传回的值将反映更改(01/01/2000)。

如果您希望将DateTime属性基本上转换为JS Date ,您可以尝试以下方法:

var jsDate = Date.parse('@Model.EndDate.ToUniversalTime().ToString("r")');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM