我的申请:MVC,C#,Razor
我有一张Dictionary
表。它有两个外键:LanguageFrom
和LanguageTo
。
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)
问题是我的下拉列表都列出了列表中的第一项而不是当前选中的项。
我做错了什么?
答案 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)
框架会自行从LanguageFrom
和LanguageTo
属性中获取值。