简体   繁体   中英

asp.net c# how to handle null?

I'm working on a project where I report Time Reports. Right now I am working on a feature where you can report vacation. From and to date. But when you just click the button send without having to enter anything in my two fields it will crash due null exception.

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

When debugging it, it doesn't hit this code block unless my fields have values in them.

You probably just need your action to have nullable parameters:

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

Do note a DateTime value cannot be null as it's a value type (it's a struct). You have to make it nullable, ie using Nullable<DateTime> or DateTime? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM