简体   繁体   English

用一天中的剃须刀填充下拉列表

[英]Populating drop down list with hours of the day razor

I am trying to populate the dropdown list with hours of the day using razor (mvc 5). 我正在尝试使用剃刀(mvc 5)在一天中的几个小时填充下拉列表。 I used one of the examples I found: 我使用了发现的示例之一:

@Html.DropDownListFor(Model => Model.StartTime,
    Enumerable.Range(00, 24).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }), "-- Hour --")

It shows the list, but as far as I understand since I used .ToString() it converted hours of the day (that I defined start time as integer in my model) to string and suppressed all leading zeros. 它显示了列表,但据我所知,因为我使用了.ToString()它将一天中的小时数(我在模型中将开始时间定义为整数)转换为字符串,并取消了所有前导零。 What method I can use to display hours in 24 hour format, and let's say I want my default to show instead of literal Hour some hour of the day, For example 06. 我可以使用什么方法以24小时格式显示小时,假设我要在一天中的某个小时显示默认值,而不是原义的Hour,例如06。

It is new language for me, and learning as I go. 对我来说,这是一种新的语言,可以随时学习。

You can pad the string with leading zeros. 您可以使用前导零填充字符串。

6.ToString("D2");
// Output: 06

For a default value: (Not have been tested) 对于默认值:(未经测试)

@{ string defaultValue = string.IsNullOrEmpty(Model.StartTime) ? "06" : null; }
@Html.DropDownListFor
(
    Model =>
        Model.StartTime,
        Enumerable.Range(00, 24).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }),
        "-- Hour --",
        defaultValue
)

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

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