代码之家  ›  专栏  ›  技术社区  ›  SimonGates

如何使SelectList中的selectedItem成为动态的

  •  2
  • SimonGates  · 技术社区  · 14 年前

    我有一个选择列表:

    SelectList DropDownListOfCatergories = new SelectList(UnitOfWork.ClassifiedCategories.FindAll().OrderBy(Order()), "Category", "Category");
    

    这很好,因为你可以看到我订购的名单。现在,当有人想要编辑某个东西时,selectedItem总是默认为第一个,不管它在哪个类别。

    i、 e从数据库动态生成。

    2 回复  |  直到 14 年前
        1
  •  0
  •   hsim    10 年前

    下面是如何在助手方法中执行此操作:

    public IEnumerable<SelectListItem> GetClassifiedCategories(IEnumerable<ClassifiedCategory> categories, string selectedCategoryName)
    {
        var list=new List<SelectListItem>();
    
        foreach (var cat in categories)
        {
            var item = new SelectListItem()
                           {
                               Text = cat.Name,
                               Value = cat.Id
                            };
            if (cat.Name==selectedCategoryName)
                item.Selected = true;
            list.Add(cat);
        }
        return list;
    }
    

    很明显,您希望与id而不是名称进行比较。另外,直接调用unitofwork也是不可取的(从应用程序体系结构的角度来看)

    @Html.DropDownListFor(model=>model.ClassifiedCategoryId, Helpers.GetClassifedCategories(UnitOfWork.ClassifiedCategories.FindAll().OrderBy(Order()), Model.ClassifiedCategoryId))
    
        2
  •  0
  •   Mike Hildner    14 年前

    不知道我是否明白。您的意思是要指定所选项目吗?如果是这样的话(我在这里使用的是mvc1.0),请使用包含4个参数的重载,例如。

    SelectList DropDownListOfCatergories = new SelectList(UnitOfWork.ClassifiedCategories.FindAll().OrderBy(Order()), "Category", "Category", "My Selected Item");