使用 jQuery 日期选取器,“创建”视图无法正常工作

本文关键字:常工作 工作 视图 选取 日期 jQuery 创建 使用 | 更新日期: 2023-09-27 18:18:06

我将 ASP.NET MVC3与Razor View一起使用,并尝试使用Scott Allen的方式替换DateTime类型的日期选择器。所以我有一个简单的模型,如下所示:

public class Student
{
    public long Id { get; set; }
    [Required]
    public string Name { get; set; }
    [DataType(DataType.DateTime)]
    public DateTime EnterYear { get; set; }
}

在进行任何更改之前,所有视图都正常工作,但是当我添加一些代码以使用数据选择器时,我遇到了一个问题:编辑视图工作正常,但是当我尝试转到创建视图时出现错误:

The model item passed into the dictionary is null, but this dictionary requires a non-
null model item of type 'System.DateTime'.
Description: An unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the error and where 
it originated in the code.
Exception Details: System.InvalidOperationException: The model item passed into the
dictionary is null, but this dictionary requires a non-null model item of type 
'System.DateTime'.
Source Error:
Line 59:         </div>
Line 60:         <div class="editor-field">
Line 61:             @Html.EditorFor(model => model.EnterYear)
Line 62:             @Html.ValidationMessageFor(model => model.EnterYear)
Line 63:         </div>
Source File: d:'Projects'MyProject'Views'Student'Create.cshtml    Line: 61 

有我的更改:

1-将编辑器模板文件夹添加到视图中的共享文件夹。

2-将日期时间部分视图添加到上面的文件夹:

@model System.DateTime
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue
, new { data_datepicker = true })

3-将新脚本添加到_Layout视图:

/// <reference path="../Scripts/jquery-1.5.1-vsdoc.js" />
/// <reference path="../Scripts/jquery-ui-1.8.11.js" />
$(document).ready(function () {
$(":input[data-datepicker]").datepicker();
})

4-并将所需的脚本和css引用添加到_Layout:

 <link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet"
 type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript">
</script>

通过此实现,"编辑"视图与数据选取器一起正常工作,但 crate 视图运行错误,"创建视图"会发生什么? 问题出在哪里?

使用 jQuery 日期选取器,“创建”视图无法正常工作

@model System.DateTime
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue
, new { data_datepicker = true })

应该是

@model System.DateTime?
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue
, new { data_datepicker = true })

允许空文本框值