【问题标题】:Why DropDown List show Dates included Time, not just Date? [duplicate]为什么下拉列表显示包含时间的日期,而不仅仅是日期? [复制]
【发布时间】:2017-08-17 04:15:14
【问题描述】:

我有日期列表,在控制器中我为下拉列表创建代码,在表中我放置日期格式的日期,也在模型中我配置广告 dd/MM/yyyy,在下拉列表中我得到包含日期的时间,但是我只需要列表中的日期。

控制器中的代码:

ViewBag.Datum = new SelectList(db.tbl_relacii.Where(x => x.DatumR >= date), "DatumR", "DatumR");

查看代码:

@Html.DropDownList("Datum", null, htmlAttributes: new { @class = "form-control" })

型号代码:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
[Column(TypeName = "date")]
public DateTime DatumR { get; set; }

这是数据库中的数据:

如何在下拉列表中获取正确的数据

【问题讨论】:

  • 你能显示控制器代码吗?为什么不在控制器中返回模型?
  • 问题已编辑,包括完整的控制器代码和下拉列表中的图像。
  • uɐpuɐɥƆ - 我试过了,但是页面被放下了。 LINQ to Entities 无法识别方法 'System.String ToString(System.String)' 方法,并且该方法无法转换为存储表达式。
  • 你试过下面的解决方案了吗?
  • 我正在尝试尚未完成,我在 .ToShortDateString(); 处有红线;和错误:不包含 'ToShortDateString' 的定义并且没有扩展方法 'ToShortDateString'''...等

标签: asp.net-mvc entity-framework razor model-view-controller


【解决方案1】:

修改您的控制器代码,如下所示

   public ActionResult Create()
    {
        var date = DateTime.Now.Date;
        ViewBag.AgentID = new SelectList(db.tbl_agenti, "aID", "agent_ime");
        ViewBag.patnikID = new SelectList(db.tbl_patnici, "pID", "ime");
        ViewBag.stanicaDO = new SelectList(db.tbl_stanici, "sID", "stanica");
        ViewBag.stanicaOD = new SelectList(db.tbl_stanici, "sID", "stanica");
        var tempList = db.tbl_relacii.Where(x => x.DatumR >= date).ToList();
        var options = new List<SelectListItem>();
        foreach(var item in tempList)
        {
            options.Add(new SelectListItem() 
            { 
                Text = item.ToString("d"), 
                Value = item
            };  
        }
       ViewBag.Datum = options;

        return View();
    }

在你看来,定义如下

 @Html.DropDownList("Datum", ViewBag.Datum as SelectList, "--Select--",
   new
   {
       @Id = "drpDatum",
       @class = "form-control"
   })

【讨论】:

    猜你喜欢
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 2022-01-18
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 2022-12-10
    相关资源
    最近更新 更多