Custom DropDownList in MVC

I want to create DropDown in MVC using Custom Range as Starting is 2000 and Ending is Current Yaer.

I have this method:

public static void BindYearDropDown(ref DropDownList dropDown, int startYear, int endYear)
    {
        dropDown.Items.Clear();

        for (int i = startYear; i <= endYear; i++)
        {
            dropDown.Items.Add(new ListItem(ConvertTo.String(i), ConvertTo.String(i)));
        }
    }

How to add use this method in Controller and View

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Change your code in Model

public string years{ get; set; }
public List<SelectListItem> yearList{ get; } = new List<SelectListItem>();
public static void BindYearDropDown(int startYear, int endYear)
{
    for (int i = startYear; i <= endYear; i++)
    {
        yearList.Add(new SelectListItem{Text = ConvertTo.String(i), Value = 
        ConvertTo.String(i)});
    }
}

In your controller set like this

//Pass value as per your requirements in BindYearDropDown()
model.BindYearDropDown(2000,endyear);

In your view

@Html.DropDownListFor(m => m.years, Model.yearList, null, new { @class = "form-control", id = "years" }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x