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