Html.DropDownListFor 有预选项目

Html.DropDownListFor with pre- selected item

我的应用程序:MVC、C#、Razor

我有一个Dictionarytable。它有两个外键:LanguageFromLanguageTo

public ActionResult Edit(int id = 0)
    {
        Dictionary dictionary = db.Dictionary.Single(d => d.DictionaryId == id);
        if (dictionary == null)
        {
            return HttpNotFound();
        }
        ViewBag.LanguageFrom = new SelectList(db.Language, "LanguageId", "Name", db.Language.First(a => a.LanguageId == dictionary.LanguageFrom));
        ViewBag.LanguageTo = new SelectList(db.Language, "LanguageId", "Name", db.Language.First(a => a.LanguageId == dictionary.LanguageTo));
        return View(dictionary);
    }

现在我需要显示两个带有预选语言的下拉列表:

@Html.DropDownListFor(x => x.LanguageFrom, (ViewBag.LanguageFrom as SelectList))
@Html.DropDownListFor(x => x.LanguageTo, ViewBag.LanguageTo as SelectList)  

问题是我的下拉列表都显示列表中的第一个项目,而不是当前选择的项目。

我做错了什么?

模型的 属性 名称不应与 ViewBag (ViewData) 键匹配。对您的代码进行以下更改:

public ActionResult Edit(int id = 0)    
{
    Dictionary dictionary = db.Dictionary.Single(d => d.DictionaryId == id);
    if (dictionary == null)
    {
        return HttpNotFound();
    }

    // change the ViewBag key for the collection of languages to something else
    // as it matches the LanguageFrom & LanguageTo properties of the Dictionary object
    ViewBag.Languages = new SelectList(db.Language, "LanguageId", "Name");
    return View(dictionary);
}

@Html.DropDownListFor(x => x.LanguageFrom, ViewBag.Languages as SelectList)
@Html.DropDownListFor(x => x.LanguageTo, ViewBag.Languages as SelectList)

框架将自行从 LanguageFromLanguageTo 属性中选取值。