mvc下拉列表未显示所选索引
本文关键字:索引 显示 下拉列表 mvc | 更新日期: 2023-09-27 18:27:00
我的控制器上有以下内容:
string preferredLanguage = "fr-ca";
ViewData["Languages"] = new SelectList(languages, "Code", "Name", preferredLanguage);
在视图上:
@Html.DropDownList("Languages", (SelectList)ViewData["Languages"], new { id = "Languages" });
我的问题是,我的下拉列表没有将所选的下拉列表索引设置为首选语言,该语言应该是法语。
注:
languages
:内的值
1) Name = "English"
Code = "en-us"
2) Name = "French"
Code = "fr-ca"
下拉列表显示两种语言,英语和法语。英语被设置为选定的索引,但我想要的是法语。
我之所以以这种方式显示languages
,是因为这个对象是从数据库中检索的,而不是通过硬编码。提前感谢!
我建议使用绑定到模型的强类型助手;大致如下:
型号:
public class LanguageFormModel
{
public string SelectedLanguage { get; set; }
public SelectList Languages { get; set; }
}
操作:
[HttpGet]
public ActionResult YourActionName()
{
// replace this with however you're getting your language variable
var languages = new CollectionOfSomeSort();
var model = new LanguageFormModel()
{
SelectedLanguage = "fr-ca",
Languages = new SelectList(languages, "Code", "Name", "fr-ca")
};
return View(model);
}
视图:
@model Your.Fully.Qualified.Namespace.LanguageFormModel
@Html.LabelFor(m => m.SelectedLanguage)
@Html.DropDownListFor(m => m.SelectedLanguage, Model.Languages, "Select one...")
就我个人而言,除了简单的消息之外,我不太喜欢使用ViewData
,即使这样,我也会使用TempData
,因为我主要只是显示确认/警报。
这对我来说很好。
Dictionary<string, string> languages = new Dictionary<string, string>() { { "en-us", "English" }, { "fr-ca", "French" } };
ViewData["Languages"] = new SelectList(languages, "key", "value", "fr-ca");
视图
@Html.DropDownList("Language", ViewData["Languages"] as SelectList, new { id = "Languages" })
这没问题:
@Html.DropDownList("languages")