Bind dropdownlist in mvc4 razor

DropDown Bind in MVC 4 Razor View

Make DDLHelper Class
public static class DDLHelper
{
        public static IList<SelectListItem> ToSelectList<T>(this IEnumerable<T> itemsToMap, Func<T, string> valueProperty, Func<T, string> textProperty, Predicate<T> isSelected = null)
        {
            var result = new List<SelectListItem>();

            if (isSelected == null)
            {
                foreach (var item in itemsToMap)
                {
                    result.Add(new SelectListItem
                    {
                        Value = valueProperty(item),
                        Text = textProperty(item),
                        //Selected = isSelected(item)
                    });
                }
            }
            else
            {
                foreach (var item in itemsToMap)
                {
                    result.Add(new SelectListItem
                    {
                        Value = valueProperty(item),
                        Text = textProperty(item),
                        Selected = isSelected(item)
                    });
                }
            }
            return result;
        }

        // Make function

        public static IList<SelectListItem> GetUserName()
        {
     IList<SelectListItem> _result = new List<SelectListItem>();
         _result = db.users.Where(p => p.is_active == true).ToSelectList(
                new Func<user, string>(p => p.id.ToString())
                , new Func<user, string>(p => p.name));
        }
}
Call in controller
ViewBag.UsersList = new SelectList(DDLHelper.GetUserType(), "Value", "Text");

Bind data to dropdown control of View (.cshtml)

call in .cshtml
If model has any default value then it will be selected in drop down, not need to pass as a selected value.
@Html.DropDownListFor(model => model.user_id, new SelectList(ViewBag.UsersList, "Value", "Text"))
Bind dropdownlist in mvc4 razor Bind dropdownlist in mvc4 razor Reviewed by Bhaumik Patel on 7:01 PM Rating: 5