1

I have a MVC action method which accept 2 date parameters. I tried to use .ToString but it gives me this error:

Returns the text representation of the value of the current Nullable object.

No overload for method 'ToString' takes 1 arguments.

I need to convert it to yyyy-MM-dd before pass it to the view. Otherwise, the textbox won't able to show the date value. Here is the code

public ActionResult Index(DateTime? dateFrom, DateTime? dateTo)
{            
    ViewBag.DateFrom = dateFrom.ToString("yyyy-MM-dd");

    return View();
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Steve
  • 2,963
  • 15
  • 61
  • 133
  • 1
    `dateFrom` is nullable, you should use `dateFrom.Value.ToString("yyyy-MM-dd")` or `dateFrom?.ToString("yyyy-MM-dd")` – phuzi Sep 11 '19 at 10:02
  • 1
    You will also have to answer the question "What date do you want to display in the view, if the nullable date is actually null?". – Matthew Watson Sep 11 '19 at 10:03

2 Answers2

2

You can use ToString like that with a normal DateTime. However you have nullable DateTime? and that won't work.

Try dateFrom.Value.ToString("yyyy-mm-dd")

Also be careful with mm (minutes) and MM (Months). I'm sure you need MM.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
TheFreaky
  • 146
  • 4
0
public ActionResult Index(DateTime? dateFrom, DateTime? dateTo)
{
    ViewBag.DateFrom = dateFrom?.ToString("yyyy-mm-dd");

    return View();
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364