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