这是我在类似情况下所做的:1)创建一个视图模型来编辑语言
public class LanguagesModel
{
public IEnumerable<int> SelectedLanguageIds { get; set; }
public MultiSelectList languages { get; set; }
}
2)在控制器中填充模型:
public ActionResult Index()
{
List<Language> languages = _languageService.GetLanguages();//however you get the languages from your datasource
var temp = new MultiSelectList(
languages.Select(l => new { Value = l.LanguageId.ToString(), Text = l.Name }),
"Value",
"Text");
LanguagesModel model = new LanguagesModel();
model.languages = temp;
return View(model);
}
3) 创建一个使用 DropDownListFor 助手的视图:
@model LanguagesModel
@using (Html.BeginForm(Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })))
{
@Html.ValidationSummary(true)
<fieldset>
@Html.ListBoxFor(m => m.SelectedLanguageIds, Model.languages)
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
小心用您实际使用的动作和控制器替换“索引”和“主页”。
编辑更改代码以使用 ListBox 而不是 DropDownList。受 Darin Dimitrov 回答的启发