Search code examples
c#asp.net-mvcrazorviewbag

Set current Date as Default Value DRopdownListFor


As the question says, i want to make the default value in my Html.DropdownList to be the Actual Date in format yyyy-mm-dd, but i dont know how to set it :

This is my Controller ViewBag:

foreach (var item in db.Pos.Select(l => l.Fecha).Distinct())
        {
           dateday = item.ToString("yyyy-MM-dd");
           lines = dateday.Split(' ')[0];
           listItem2.Add(lines);
        }
        var fechas = new SelectList(listItem2.ToList());
        ViewBag.Fechas = fechas;

And this is my View HtmlDRopdown:

     @Html.DropDownList("Fechas", "Todas")

How can i set a defaut value based on the actual date?


Solution

  • Assuming your LINQ expression b.Pos.Select(l => l.Fecha).Distinct() returns a collection of DateTime.

    var list = new List<SelectListItem>();
    var today = DateTime.Now;
    foreach (var item in db.Pos.Select(l => l.Fecha).Distinct())
    {
       var dateday = item.ToString("yyyy-MM-dd");
       var listItem = new SelectListItem { Value = dateday, Text = dateday };
       listItem.Selected = today.Day == item.Day;
       list.Add(listItem);
    }
    ViewBag.Fechas = list;
    

    And in your view,

    @Html.DropDownList("Fechas")
    

    This will generate a SELECT Element with name "Fechas" with the days(in the format we specified) and todays date will be selected.

    If you want your select element to have a different name, you may consider using a different overload such as

    @Html.DropDownList("MyCustomElementName",ViewBag.Fechas as List<SelectListItem>)
    

    I personally prefer to not use ViewBag ! I like to use a view model and the DropDownListFor helper method.