具有预选项目的Html.DropDownListFor

时间:2015-02-01 17:49:36

标签: asp.net-mvc razor html.dropdownlistfor

我的申请:MVC,C#,Razor

我有一张Dictionary表。它有两个外键: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)  

问题是我的下拉列表都列出了列表中的第一项而不是当前选中的项。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

模型的属性名称不应与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属性中获取值。