c# - asp.net c#如何处理null?

标签 c# asp.net

我正在做一个报告时间报告的项目。现在我正在开发一个可以报告假期的功能。从和到现在。但是,当您只需单击发送按钮而无需在我的两个字段中输入任何内容时,它将因空异常而崩溃。

[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();
}

调试时,除非我的字段中有值,否则它不会命中此代码块。

最佳答案

您可能只需要您的操作具有可为空的参数:

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

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

关于c# - asp.net c#如何处理null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32761631/

相关文章:

c# - 检查身份电子邮件 token 有效性

c# - 可序列化与数据契约与 WCF 服务中什么都没有

javascript - 从 javascript 调用 WCF 方法

c# - ASP.Net MVC 忽略过滤器顺序

c# - 在 Visual Studio 中开发 Azure Function 时存储帐户无效

c# - 分组 2 个表,计算值,然后将结果保存在字典中

c# - Parallel.ForEach 添加到列表

javascript - 当文本更改且文本框不失去焦点时调用方法

c# - FindByIdentity 在 ASP.NET webapp 中因 PricipalOperationException 而失败

javascript - 防止点击链接按钮时刷新页面