【发布时间】:2025-12-18 09:25:01
【问题描述】:
我正在开发一个 asp.net mvc-4 Web 应用程序。我有以下字段:-
<div>
@Html.TextBoxFor(model => model.LiveDate, new { @class = "datepicker", @Value = (Model != null && Model.LiveDate.HasValue) ? Model.LiveDate.Value.ToString("dd/MM/yyyy") : string.Empty })
@Html.ValidationMessageFor(model => model.LiveDate)
</div>
<div>
@Html.TextBoxFor(model => model.EndDate, new { @class = "datepicker", disabled = "disabled",@Value = (Model != null && Model.EndDate.HasValue) ? Model.EndDate.Value.ToString("dd/MM/yyyy") : string.Empty })
@Html.ValidationMessageFor(model => model.EndDate)
</div>
<div>
@Html.EditorFor(model => model.ContractLength)
@Html.ValidationMessageFor(model => model.ContractLength)
</div>
现在我定义了以下 jquery,它应该将 LiveDate 和 ContractLength 发送到一个操作方法来设置 EndDate:-
$("#LiveDate, #ContractLength").change(function () {
$.getJSON("@Url.Content("~/Order/CalculateDate")", { date: $("#LiveDate").val(), month: $("#ContractLength").val() },
function (Data) {
$("#EndDate").val(Data.Name);
});
});
这是执行计算的实际操作方法public
public ActionResult CalculateDate(string date, int? month)
{
if (!String.IsNullOrEmpty(date) && month.HasValue)
{
DateTime d = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
var Data = new { Name = d.AddMonths(month.Value) };
return Json(Data, JsonRequestBehavior.AllowGet);
}
return Json(new { Name=string.Empty}, JsonRequestBehavior.AllowGet);
}
现在我尝试了这个:-
- 住户=
31/05/2016 - 月合约长度=
7 - 动作方法返回以下
31/12/2016 00:00:00但是在 EndDate 中我得到了这个值/Date(1483142400000)/而不是"31/12/2016".. 那么任何人都可以提出相应的建议吗?
【问题讨论】:
-
这是 MVC 的默认序列化行为。 See this answer on * for options.
-
@JohnMc 以及如何解析序列化?
-
您应该接受 DateTime 对象而不是字符串。一旦您在 Newton Soft Json.Net 之类的东西上设置了 Json 序列化设置,它就会起作用。 newtonsoft.com/json/help/html/datesinjson.htm
-
@JohnMc 但在我看来,我正在使用 .ToString() 将日期时间解析为字符串……这就是为什么如果我修改操作方法以接受日期时间,我将始终收到 null ..
标签: javascript jquery json asp.net-mvc razor