這是我做類似的情況: 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。由達林季米特洛夫的回答啓發