Tuesday, May 10, 2016

Setting the default value on a SelectList in ASP.NET MVC

If you have ever encountered the issue whereby you needed to set a default value on a SelectList (for a dropdownlist control), then you might be wondering how to accomplish this!

For example, if you have a SelectList like the following:


List<SelectListItem> selectList = new List<SelectListItem>() { new SelectListItem() { Text = "IN", Value = "IN" }, new SelectListItem() { Text = "MI", Value = "MI" } };

Then you may want to set a default value for the SelectList as follows:


public List<SelectListItem> GetSelectedValueList(List<SelectListItem> selectList, string selectedValue)
        {
            List<SelectListItem> newSelectList = new List<SelectListItem>();
            foreach (var item in selectList)
            {
                var selectListItem = new SelectListItem() { Text = item.Text, Value = item.Value, Selected = false };

                //if the selected item matches
                if (item.Value.Equals(selectedValue))
                {
                    selectListItem.Selected = true;
                }//if

                newSelectList.Add(selectListItem);
            }//foreach

            return newSelectList;
        }

Now when you pass in an existing SelectList, you will get it populated with a default value like so:

model.State = GetSelectedValueList(selectList, "MI");

return View(model);

That is all there it to it!!

No comments:

Post a Comment