DateTime时间被验证为日期和时间

时间:2013-01-30 00:45:29

标签: c# datetime asp.net-mvc-4

所以我有这个表格,用户可以输入开始时间和结束时间(预订)。数据库中的值是DateTimes,但Date部分完全被忽略。目前,当我进入例如。 “下午5:00”(通过jQuery时间选择器),它说这不是一个有效的日期。如果我输入“30/1/2013 5:00 pm”,它会将此视为有效...如何将此行为更改为仅作为时间验证? (或者,如果这不是理想的,我怎样才能完全关闭该字段的验证 - 我将在控制器中手动处理验证)

我看到了这个:http://connect.microsoft.com/VisualStudio/feedback/details/705643/a-data-val-date-attribute-is-generated-for-time-fields-in-asp-net-mvc-4#但是微软声称它已经修复了;不确定这是否是同一个问题。我不想将数据库定义更改为TimeSpan,因为我相信它会破坏现有数据(它不会吗?)。

控制器:

[HttpPost]
    public ActionResult Create(BookingDetailsDate bookingdetailsdates) //, FormCollection collection)
    {
        if (ModelState.IsValid)
        {
            try
            {
                //bookingdetailsdates.StartTime = DateTime.Parse(collection["StartTime"]); // TODO: do this better
                //bookingdetailsdates.EndTime   = DateTime.Parse(collection["EndTime"]);
                bookingdetailsdatesRepository.Add(bookingdetailsdates);
                bookingdetailsdatesRepository.Save();
                return RedirectToAction("Index", new { id = bookingdetailsdates.BookingDetailsID });
            }
            catch { }
        }
        return View(bookingdetailsdates);
    }

查看:

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend></legend>
...
    @Html.EditorFor(model => model.StartTime)

    @Html.EditorFor(model => model.EndTime)

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>
}

编辑模板:

<div class="editor-label">
    @Html.LabelFor(m => m)
</div>
<div class="editor-field">
    @if (Model.HasValue==true)
    {
        @Html.TextBox("", Model.Value.ToShortTimeString(), new { @class = "TimePicker" })
    }
    else
    {
        @Html.TextBoxFor(m => m, new { @class = "TimePicker" })
    }

    @Html.ValidationMessageFor(m => m)

</div>

2 个答案:

答案 0 :(得分:0)

我认为“DateTime”这个数据类型不是一个好选择,如果你只是想节省用户保存的时间,然后在我建议使用“nchar”类型的地方比较它们。为什么?让我解释一下,datetime是一个非常复杂的类型,它有多种形式。像“2013-1-29 5:00 pm”,“2013/1/29 5:00 pm”。如果您的目的是比较并检查是否过时,您可以使用这种方式。 “201301291700”,它的固定长度为12.这样做的好处是1.您可以通过类型字符串轻松保存它。 2.你可以通过转换为int类型或者长类型来轻松比较。(数字更容易比较,不是吗?)

答案是基于我的经验,希望它能帮到你!

答案 1 :(得分:0)

所以问题在于jQuery的验证,即使我的字段的元数据指定它只是一个时间(甚至不是绝对必要的),jQuery的验证要求该框包含一个完整的日期时间字符串......

注释掉这些行可以解决问题:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>