0

我对 ViewBag 和 DropDownListFor 有点问题。下面的代码工作正常,但我需要“手动”添加一个值为 0 的项目。有什么想法可以做到这一点吗?

public ActionResult Create()
{

            ViewBag.ParagrafyRodzic = paragrafRepository.All;

            return View();
}

@Html.DropDownListFor(model => model.ParagrafID, ((IEnumerable<Projekty03.Models.Paragraf>)ViewBag.ParagrafyRodzic)
.Select(option => new SelectListItem
{
    Text = option.ParagrafNazwa.ToString(),
    Value = option.ParagrafID.ToString(),
    Selected = (Model != null) && (option.ParagrafID == Model.ParagrafParent)
}),Translate.ChooseList)

:) Tx 寻求帮助

4

1 回答 1

1

我使用静态方法来构建 SelectList。在模型中的某处放置如下内容:

public static SelectList MakeSelectListDipendenze(SomeCollectionColl, bool emptyElem = true)
        {
            List<SelectListItem> Items = new List<SelectListItem>();
            if (emptyElem)
                Items.Add((new SelectListItem { Text = " ", Value = "-1" }));
            foreach (ElemInCollection Item in Coll)
            {
                SelectListItem AddMe = new SelectListItem();
                AddMe.Text = Item.Description;
                AddMe.Value = Item.Id.ToString();
                Items.Add(AddMe);
            }
            SelectList Res = new SelectList(Items, "Value", "Text");
            return Res;
        }

在您看来,您通过以下方式引用此内容

@Html.DropDownListFor(x => x.Field, ModelClass.MakeSelectListUtenti(Model.Destinations), new { id="Destinations"})
于 2011-10-05T10:07:06.123 回答