hashim
hashim

Reputation: 91

How to create a month dropdown in "MM" format in asp.net MVC razor view?

I want to loop through months of year with MM format , i do it but months format is 1, 2, 3, ...etc i want the format to be 01, 02, 03 how i do it

<select id="CreditCardExpiryDateMonth" class="dropdown form-control">
    @for (var iMonth = DateTime.Now.Month; iMonth <= 12; iMonth++)
    {
        <option value="@iMonth"@(DateTime.Now.Month == iMonth ? " selected" : "")>@iMonth</option>
    }
</select>

any advice

Upvotes: 0

Views: 1545

Answers (3)

adiga
adiga

Reputation: 35242

Since you're using MVC, you can use SelectList and Html.DropdownList helpers to populate your dropdown and pre-select a value:

@Html.DropDownList("CreditCardExpiryDateMonth",
    new SelectList(Enumerable.Range(1, 12).Select(a => new { Text = a.ToString("00"), Value = a }),
                        "Value", 
                        "Text", 
                        DateTime.Today.Month),
    new { @class = "dropdown form-control" })

How this works:

  • @Html.DropDownList("CreditCardExpiryDateMonth"): Creates a select element with name and id as: "CreditCardExpiryDateMonth"
  • The second parameter in this overload of DropDownList is the SelectList. We usually get this from the database and assign to ViewBag in the controller. But in your case, we can use the Enumerable.Range to generate 12 numbers and format them to proper strings. In this overload of the SelectList, 4th parameter is the selectedValue. This is used to pre-select a value in the dropdown. In your case, it is Today's month.

  • The final parameter is the htmlAttributes. Here, we add class to the select element.

This approach is flexible and cleaner. Should your requirement change to displaying month names with globalization or something else, you only have to change the SelectList logic.

Upvotes: 0

Connor
Connor

Reputation: 897

You can use ToString to format the int.

<select id="CreditCardExpiryDateMonth" class="dropdown form-control">
     @for (var iMonth = 1; iMonth <= 12; iMonth++)
     {
         <option value="@iMonth"@(DateTime.Now.Month == iMonth ? " selected" : "")>@iMonth.ToString("00")</option>
     }
</select>

Upvotes: 4

Deja
Deja

Reputation: 356

To make the format MM or 01 etc, try this:

DateTime.Now.Month.ToString("d2")

Upvotes: -1

Related Questions