SelectList ToShortDateString viewbag

时间:2015-04-29 04:41:33

标签: c# asp.net-mvc entity-framework

我的项目是MVC5,使用EF 6.1;我使用以下内容生成下拉列表:

型号:

public partial class LogBook
{
    public string ID { get; set; }
    public string TheName { get; set; }
    public System.DateTime Day { get; set; }
}

控制器:

var list = db.LogBook.Where(i => i.TheName == xxx).OrderByDescending(x => x.Day).ToList();
ViewBag.Logbooks = new SelectList(list, "ID", "Day");

查看:

@Html.DropDownList("logbookdate", ViewBag.LogBooks  as SelectList) 

结果显示:

11/11/2014 12:00 AM

我该如何显示日期?

2 个答案:

答案 0 :(得分:0)

试试这个:

var list = db.LogBook.Where(i => i.TheName == xxx).Select(d=> new {ID= d.TheName, Day = d.Day.ToShortDateString()).OrderByDescending(x => x.Day).ToList();
 ViewBag.Logbooks = new SelectList(list, "ID", "Day");

没有切实可行,但应该有效。

编辑:

IEnumerable<SelectListItem> selectList = 
    from c in db.LogBook
    where c.TheName equals xxx
    select new SelectListItem
    {
        Text = c.ID,
        Value = c.Day.ToShortDateString()
    };

然后将它绑定到前面的dropdonwlist。

你可以尝试一下。我没有检查语法。希望它没事。

答案 1 :(得分:0)

试试这个:

var list = db.LogBook.Where(i => i.TheName == xxx).OrderByDescending(x => x.Day).ToList();

更改查询

IEnumerable<SelectListItem> selectList = db.LogBook
                                           .Where(i => i.TheName == xxx)
                                           .Select(c => new SelectListItem
                                           {
                                              Text = c.ID,
                                              Value = c.Day.ToShortDateString()                                                
                                           });