2011-02-28 74 views
6

我正在开发一个具有DateTime字段的项目。使用WebMatrix和Razor保存日期时间

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

如何保存WebMatrix和Razor中不需要的日期时间字段?

我试图做这样的事情:

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:

+0

请在代码块中发布错误而不杀死换行符。 – SLaks 2011-02-28 14:45:18

回答

4

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

DateTime? dtForecastComplete = null; 

现在你可以通过(并检索)一个空值到/从数据库。

+0

在我的代码中,我使用TryParse DateTime类,它不接受空值。 ](http://jsfiddle.net/Riderman/JV5gD/)。只要把保存。**错误:**“转换为日期时间发生溢出。 说明:在执行 转换为日期时发生了未处理的异常。“ – ridermansb 2011-02-28 16:43:52

+0

我添加了一个辅助变量以便使用TryParse,但仍然出现上述错误。 – ridermansb 2011-02-28 16:45:42

+0

这些是我在下面提到的问题。如果您在开始时没有使用可空的DateTime,则必须更改整个项目。这就是为什么在大多数情况下,“快速和肮脏”的解决方案是一个很好的节省时间的解决方法。 – 2011-03-01 11:13:11

0

如果你想要一个 “快速和肮脏” 的解决方案,我会插入DateTime.MinValue作为初始值,并在再次显示时将其测试为空。

当然,更好的方法是动态构建插入语句和值列表,如果值为空,则将其从列表中排除。

+0

有一些方法可以将null而不是Min? – ridermansb 2011-02-28 14:58:02

+0

GvS为您解答了这个问题;-)确保您在整个应用程序中更改DateTime字段的DataType,否则您将遇到Build错误。 – 2011-02-28 15:00:23

+0

使用转换:“db.Execute(sql paramters {}” – ridermansb 2011-02-28 15:05:41