是这样的,我从数据库获取了List类型的数据,通过model传到前端,List中的每一条数据,都包含了string类型的type,Name,link三个成员,type用需要用Dropdownlist绑定,其他的Name和link就直接textbox显示,但type的Dropdownlist的下拉选项是另外一个List<string>类型的,我试过将下拉选项直接转为 List<SelectListItem> 类型通过ViewData传到前台,但不知怎么写前台代码。这是我的做的一个测试的代码截图,我希望做到的效果:
但实际的效果:入门小白,求帮助

解决方案 »

  1.   

    你应该将构造SelectListItem的过程移到循环里去做,在new的时候判断value是百度还是新浪对应的值,是的话就将对应的SelectListItem赋值Selected为true
      

  2.   

    public static class SelectListExtensions
        {
            public static void AddSelectPlease(this List<SelectListItem> list)
            {
                list.Insert(0, new SelectListItem { Text = "--请选择--", Value = string.Empty });
            }
        }
        public static class SelectListHelper
        {
            public static IEnumerable<SelectListItem> Countries(int? selectValue, bool addSelectPlease = true)
            {
                List<SelectListItem> list = new List<SelectListItem>();            if (addSelectPlease)
                    list.AddSelectPlease();            CountrySearchParams parms = new CountrySearchParams();
                parms.Published = true;            var data = IocResolver.GetService<ICountryService>().GetCountries(parms).OrderBy(x => x.DisplayOrder);            foreach (var item in data)
                {
                    SelectListItem temp = new SelectListItem();
                    temp.Text = item.NameCn;
                    temp.Value = item.Id.ToString();                if (selectValue.HasValue && selectValue.Value == item.Id)
                        temp.Selected = true;                list.Add(temp);
                }            return list;
            }@Html.DropDownListFor(x => x.CountryId, SelectListHelper.Countries(Model != null ? (int?)Model.CountryId : null), new { @class = "chosen-select" })
      

  3.   

    看看:
    http://zzk.cnblogs.com/s?w=blog%3Ainsus%20mvc%20dropdownlist