【问题标题】:jQuery UI DatePicker does not set the value of TextBoxForjQuery UI DatePicker 没有设置 TextBoxFor 的值
【发布时间】:2016-04-27 02:01:47
【问题描述】:

我在 MVC 应用程序中的 HtmlTextBoxFor 上添加了 jQueryUI DatePicker。下面是我的代码。现在当我调试时,日期在create 事件中显示01/01/2001 12:00:00,而不是选择的日期。

<!-- JoinDate -->
<div class="form-group">
    <div class="editor-label">
        @Html.LabelFor(model => model.JoinDate, new { @class = "col-sm-2 control-label" })
</div>
<div class="editor-field">
    @Html.TextBoxFor(model => model.JoinDate, new { @class = "form-control", @id = "datepicker" })
    @Html.ValidationMessageFor(model => model.JoinDate)
</div>

<script src="~/Content/js/jquery.js"></script>
<script src="~/Scripts/jquery-ui-1.11.4.min.js"></script>

<script>
$(function () {
    $("#datepicker").datepicker();
});

【问题讨论】:

  • 您已经引用了 jQuery-ui 两次,您需要删除其中一个引用。我建议删除&lt;script src="~/Scripts/jquery-ui-1.11.4.js"&gt;&lt;/script&gt;
  • 仍有价值01/01/...
  • 如果你这样声明呢:$(function () { $("#datepicker").datepicker({defaultDate: ''}); });
  • 不,它没有帮助。
  • 将模型传递给视图时JoinDate的值是多少?

标签: asp.net asp.net-mvc jquery-ui jquery-ui-datepicker


【解决方案1】:

好吧,我找到了解决方案。我添加了一个input 并将其分配给jQueryUI datepicker。现在onSelect 事件,它只是将值设置为TextBoxfor。请参阅下面的代码。

<script>
$(function () {
    $("#datepicker").datepicker();
});

<script>
$('#datepicker').datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: "dd-mm-yy",
    constrainInput: true,
    defaultDate: new Date(1975, 1 - 1, 1),
    yearRange: "2000:2025",
    onSelect: function () {
        alert($('#datepicker').val());
        $('#joindate').val($('#datepicker').val());
    }
});
</script>

<!-- JoinDate -->
                        <div class="form-group">
                            <div class="editor-label">
                                @Html.LabelFor(model => model.JoinDate, new { @class = "col-sm-2 control-label" })
                            </div>
                            <div class="editor-field">
                                <input type="text" id="datepicker" onchange="onDateChange()"/>
                                @Html.TextBoxFor(model => model.JoinDate, new { @class = "form-control", @id="joindate" })
                                @Html.ValidationMessageFor(model => model.JoinDate)
                            </div>
                        </div>

【讨论】:

  • 没有理由使用defaultDate: - 如果在将模型传递给视图之前在控制器中设置了属性JoinDate 的值,那么将显示该值。
  • 其实这个控制器是要创建的。当我在 View 中使用它时,我不需要datepicker
  • 这毫无意义。你为什么要问一些不需要的问题?你为什么要使用new { id="joindate" } - id 已经是id="JoinDate"
  • 感谢您的第二个建议。我其实并不知道。对于你说的第一件事,我知道这里的人不会问任何不需要的东西。我需要为 Create 控制器实现 datepicker。在查看详细信息中,我只在 Textboxfor 中显示日期。无需在 View 中更改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
  • 1970-01-01
  • 2020-11-23
  • 1970-01-01
相关资源
最近更新 更多