c# - 使用 WebMatrix 和 Razor 保存日期时间

标签 c# asp.net razor webmatrix sql-server-ce-4

我正在开发一个包含 DateTime 字段的项目。

考虑到日期不是必填字段,我在其中使用 jQuery 让用户选择日期格式“dd/MM/yyyy”。

如何保存 WebMatrix 和 Razor 中不需要的 DateTime 字段?

我正在尝试做这样的事情:

I put only the code which I think is important to complete the code can be found here

@{
//Get data
string TaskForecastCompletion= Request["txtForecastCompletion"];
string TaskCompletedIn= Request["txtCompletedIn"];

                    DateTime dtForecastCompletion = default(DateTime);
                    if (!Request["txtForecastCompletion"].IsEmpty() && !DateTime.TryParse(Request["txtForecastCompletion"], out dtForecastCompletion))
                    {
                            ModelState.AddError("PrevisaoFinalizacao", "Data de previsão de finalização é inválida. Formato: dd/mm/aaaa");
                    }


                                    sql = @"update Tasks set Title = @0 ,Description = @1 ,ProjectID = @2 ,ForecastCompletion = @3 ,RequestBy = @4 ,CompletedIn = @5 ,Modified = getdate() ,Priority = @6 where ID = @7";
                                    db.Execute(sql, TaskTitle,TaskDescription, ProjectID, dtForecastCompletion, TaskRequestBy, dtTaskCompletedIn, TaskPriority, TaskID);
}

尝试更改时出错

An overflow occurred while converting to 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.Data.SqlServerCe.SqlCeException: An overflow occurred while converting to datetime.

Source Error:

Line 62: { Line 63:
sql = @"update Tasks set Title = @0 ,Description = @1 ,ProjectID = @2 ,ForecastCompletion = @3 ,RequestBy = @4 ,CompletedIn = @5 ,Modified = getdate() ,Priority = @6 where ID = @7"; Line 64:
db.Execute(sql, TaskTitle,TaskDescription, ProjectID, dtForecastCompletion, TaskRequestBy, dtTaskCompletedIn, TaskPriority, TaskID); Line 65:
} Line 66:

最佳答案

如果数据库中的日期字段可以为空(未标记为 NOT NULL),则可以将 C# 中的数据类型更改为 nullable DateTime :

 DateTime? dtForecastComplete = null;

现在您可以向/从数据库传递(和检索)空值。

关于c# - 使用 WebMatrix 和 Razor 保存日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5143385/

相关文章:

c# - 如何从单个解决方案生成多个 .exe 文件?

c# - ASP.NET 5 Web 项目中的 Entity Framework Core - 自动生成 LINQ 过滤器查询

c# - Azure 存储文件强制下载到浏览器

c# - 在控制台应用程序中使用Razor的最佳方法是什么

asp.net - 使用 linq 从两个表(连接)中获取数据并将结果返回到 View 中

asp.net-mvc-3 - 为什么 @Html.HiddenFor 设置指定以外的其他模型属性的值?

c# - NHibernate OutOfMemoryException 查询大字节 []

c# - 使用 ProtectedData.Protect 时的 DataProtectionScope

c# - 在单元测试中将 DI 与没有依赖关系的模块/类一起使用是否有令人信服的理由?

c# - C#中如何创建一个对象的实例