简体   繁体   中英

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). 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. 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.

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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