简体   繁体   English

将当前日期设置为默认值DRopdownListFor

[英]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 : 如问题所述,我想将Html.DropdownList中的默认值设置为yyyy-mm-dd格式的“实际日期”,但是我不知道如何设置它:

This is my Controller ViewBag: 这是我的控制器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: 这是我的View HtmlDRopdown:

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

How can i set a defaut value based on the actual date? 如何根据实际日期设置默认值?

Assuming your LINQ expression b.Pos.Select(l => l.Fecha).Distinct() returns a collection of DateTime . 假设您的LINQ表达式b.Pos.Select(l => l.Fecha).Distinct()返回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. 这将生成一个名称为“ Fechas”的SELECT元素,并带有日期(以我们指定的格式)和今天的日期。

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 ! 我个人更喜欢不使用ViewBag! I like to use a view model and the DropDownListFor helper method . 我喜欢使用视图模型和DropDownListFor helper方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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