Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a default value to a DateTime parameter

In my MVC application I want to set default values to the DateTime parameter.

[HttpPost]
public ActionResult BudgetVSActualTabular(DateTime startDate)
{
    var Odata = _db.sp_BudgetedVsActualTabular(startDate).ToList();    
    string[] monthName = new string[12];    
    for (int i = 0; i < 12;i++ )
    {
        DateTime date = startDate;
        date = date.AddMonths(i);
        monthName[i] = date.ToString("MMMM") + " " + date.Year.ToString();     
    }

    ViewBag.startDate = new SelectList(_db.DaymonFinancialYears, "startDate", "DateRange");    
    var MonthName = monthName.ToList();
    ViewBag.Bdata = Odata;
    ViewBag.Cdata = MonthName;
    return View();
}
like image 882
Shahzad Ahamad Avatar asked Jan 20 '16 10:01

Shahzad Ahamad


People also ask

What is the default value for DateTime?

The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight). The maximum value can be December 31, 9999 11:59:59 P.M. Use different constructors of the DateTime struct to assign an initial value to a DateTime object.

What is default C#?

A default value expression produces the default value of a type. There are two kinds of default value expressions: the default operator call and a default literal. You also use the default keyword as the default case label within a switch statement.


1 Answers

You cannot set a null to a DateTime but you can use a Nullable DateTime parameter instead:

[HttpPost]
public ActionResult BudgetVSActualTabular(DateTime? startDate = null )
{ 
    if (startDate == null)
    {
        startDate  = new DateTime(2016, 06, 01);
    }
    //You should pass startDate.Value
    var Odata = _db.sp_BudgetedVsActualTabular(startDate.Value).ToList();

}
like image 131
Salah Akbari Avatar answered Sep 17 '22 15:09

Salah Akbari