我在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求助
答案 0 :(得分: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;
}
在你的wiew中,你可以通过
来引用它@Html.DropDownListFor(x => x.Field, ModelClass.MakeSelectListUtenti(Model.Destinations), new { id="Destinations"})