2015-09-24 50 views
1

我正在研究一个报告时间报告的项目。现在我正在研究一个可以报告假期的功能。从迄今为止。但是当你只需点击发送按钮而不必在我的两个字段中输入任何内容时,它将因空的异常而崩溃。asp.net c#如何处理null?

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Index(DateTime fromDate, DateTime toDate, string comment) 
{ 
    using (IDatabaseLayer db = new DatabaseLayer()) 
    { 
     if (fromDate != null || toDate != null) 
     { 
      db.InsertVacation(Constants.CurrentUser(User.Identity.Name), fromDate, toDate, comment); 
      ViewData.Model = db.GetUserVacations(Constants.CurrentUser(User.Identity.Name)); 
     } 
    } 

    SendVacationMail(fromDate, toDate, comment); 
    ViewData["posted"] = true; 

    return View(); 
} 

调试它时,它不会碰到这个代码块,除非我的字段中有值。

+0

@codroipo但如果我的值为null,它甚至不会击中该块。 –

+1

使用'&&''opereator而不是'||' – Sybren

+0

@Sybren不管我使用什么操作符,如果我的字段为空,并且我按下提交,它不会碰到这个块 –

回答

8

你可能只需要你的行动,有可为空参数:

public ActionResult Index(DateTime? fromDate, DateTime? toDate, string comment) 
{ 
} 

请注意一个DateTime值不能为空,因为它是值类型(这是一个结构)。您必须将其设为空,即使用Nullable<DateTime>DateTime?

+0

对,我应该尽管这样..谢谢。 –

+0

@foobar你为什么不把问题标记为已回答?好,男人! – KarmaEDV

+0

因为当e第一次发布它时,我试过了,当它做到了时,我被goong接受了,但是我无法接受它10分钟,我忘记了。呵呵,谢谢你提醒我。 –