c# - 使用 jQuery 日期选择器和创建 View 无法正常工作

标签 c# jquery asp.net-mvc datepicker

我将 ASP.NET MVC3 与 Razor View 一起使用,并尝试使用 Scott Allen's way替换 DateTime 类型的 datepicker。 所以我有一个像这样的简单模型:

public class Student
{
    public long Id { get; set; }

    [Required]
    public string Name { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime EnterYear { get; set; }

}

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

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- 将 EditorTemplates 文件夹添加到 View 中的共享文件夹。

2-将日期时间部分 View 添加到上述文件夹:

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

3- 将新脚本添加到 _Layout View :

/// <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>

通过此实现,编辑 View 可以与数据选择器一起正常工作,但 crate View 运行错误,创建 View 会发生什么情况?问题出在哪里?

最佳答案

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

应该是

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

允许空文本框值

关于c# - 使用 jQuery 日期选择器和创建 View 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8551059/

相关文章:

c# - 是否有可能在构造函数中违反 Liskov 替换原则?

javascript - 在没有回发的情况下从 LinkBut​​ton 调用 C# 方法(使用 PageMethod)(MasterPage 网站)

jquery - MVC 3 - 客户端验证列表

javascript - 将数据从js发送到servlet并返回响应

asp.net-mvc - 谁负责加载数据?

c# - 使用自定义 TextWriter 时 OutputStream 不可用 mvc

c# - 按钮已禁用 - DialogHost 和日历

c# - 如何在 Windows 8 (WinRT) 上从图像创建视频

javascript - 如何在 jQuery 中定位不是具有特定类的容器子级的容器?

ASP.NET MVC : How do other people apply conditional CSS classes?