没有模型绑定DateTime字段时如何使用JQueryUI Datepicker?

How to use JQueryUI Datepicker when there is no model to bind the DateTime field?

我已经在另一个视图上使用这个日期选择器,一个接收模型的 Create() 视图,然后我可以使用以下方法显示日期选择器:

<link rel="stylesheet"href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">

...  
@Html.EditorFor(model => model.OrderDate, new { htmlAttributes = new { @class = "form-control", placeholder = "OrderDate", @readonly = "true" } })

...

@section Scripts
{
@Scripts.Render("~/bundles/jqueryui")
<script type="text/javascript">
    jQuery.validator.methods["date"] = function (value, element) { return true; }
    $(document).ready(function () {
        $("#OrderDate").val("");
        $('input[type=datetime]').datepicker({
            dateFormat: 'dd/mm/yy',
            changeMonth: true,
            changeYear: true,
            yearRange: "-1:+2",
            onClose: function (dateText, inst) {
                $("#cmdEnter").focus();
            }
        });
    });
</script>
}

现在的问题是我需要在视图中使用日期选择器作为顶部的搜索字段之一,我正在尝试按范围实施日期搜索。此视图是一个索引,这意味着它不接收模型它接收模型集合(在本例中为 PageList):

@model PagedList.IPagedList<EntregaMedicamentos.Models.PedidoDisprofarmaViewModel>

所以,在这种情况下我不能使用模型 => model.OrderDate,然后我尝试使用 Viewbag 在那里传递那个日期,比如..

@Html.TextBox("searchDateFrom", ViewBag.currentFilter2 as DateTime?, new { @class = "form-control", placeholder = "Desde fecha", @readonly = "true" })

所以我从 EditorFor 更改为 TextBox 并尝试使用 Editor,但日期选择器仍然不想在单击时弹出,有什么想法吗?

这是试过了,还是没有弹窗:

@Html.TextBox("searchDateFrom", ViewBag.currentFilter2 as DateTime?, new { @class = "form-control", placeholder = "Desde fecha", @readonly = "true" })

....

@section scripts
{
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/cssjqryUi")

<script type="text/javascript">
    jQuery.validator.methods["date"] = function (value, element) { return true; }
    $(document).ready(function () {
        $("#searchDateFrom").val("");
        $('input[type=datetime]').datepicker({
            dateFormat: 'dd/mm/yy',
            changeMonth: true,
            changeYear: true,
            yearRange: "-1:+2",
            onClose: function (dateText, inst) {
                $("#cmdSearch").focus();
            }
        });
    });
</script>
...

谢谢!!

您可以使用

<input type="datetime" name="ordredate">

因为@Html.TextBox() 没有生成文本框类型 'datetime'。

您可以像这样在 TextBox 助手中附加 type="datetime" 属性:

@Html.TextBox("searchDateFrom", ViewBag.currentFilter2 as DateTime?, new { @class = "form-control", placeholder = "Desde fecha", 
              @readonly = "readonly", type = "datetime" })

然后在日期选择器中添加与提供的格式匹配的DisplayFormatAttribute

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime searchDateFrom { get; set; }

请注意,@Html.TextBox() 助手默认生成 <input type="text" /> 元素,您需要指定 type="datetime" 以启用 jQuery 代码中提供的日期时间日历选择器。

您可以在 this fiddle 中查看日期选择器实现的示例。