asp.net c#如何处理null?

foo*_*bar 1 c# asp.net

我正在开展一个报告时间报告的项目.现在我正在开发一个可以报告假期的功能.从迄今为止.但是,当您只需单击按钮发送而无需在我的两个字段中输入任何内容时,它将因为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();
}
Run Code Online (Sandbox Code Playgroud)

在调试它时,它不会触及此代码块,除非我的字段中包含值.

ken*_*n2k 8

您可能只需要您的操作就可以使用可为空的参数:

public ActionResult Index(DateTime? fromDate, DateTime? toDate, string comment)
{
}
Run Code Online (Sandbox Code Playgroud)

请注意,DateTime值不能为null,因为它是值类型(它是结构).你必须使它可以为空,即使用Nullable<DateTime>DateTime?.