1

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.

4
  • @codroipo But it dosen't even hit the block if my values are null. Commented Sep 24, 2015 at 12:44
  • 1
    use && opereator instead of || Commented Sep 24, 2015 at 12:44
  • @Sybren dosen't matter what operator I use, if my fields are null and I press submit it dosen't hit this block Commented Sep 24, 2015 at 12:44
  • even if the block isn't hit || is the wrong operator here if you want both values not to be null Commented Sep 24, 2015 at 12:45

1 Answer 1

8

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, i.e. using Nullable<DateTime> or DateTime?.

Sign up to request clarification or add additional context in comments.

3 Comments

Right, I I should have though of that.. Thanks.
@foobar Why don't you mark the question as answered? Be nice, man!
Because when e first posted it i tried and when it did work i were goong to accepterade it, but i could not accept it for 10 mins and i forgot. Hehe, thanks for reminding me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.