Darshan Unadkat
Darshan Unadkat

Reputation: 151

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

Upvotes: 0

Views: 83

Answers (1)

user14490199
user14490199

Reputation:

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" }

Upvotes: 2

Related Questions