你需要在控制器與更復雜的模型的工作不僅僅是int[]
:
public class CheckedListModel
{
public bool IsChecked { get; set; }
public int SelectedValue { get; set; }
public SelectList Items { get; set; }
}
樣本,以便使這種模型的列表:
@model CheckedListModel[]
@using (Html.BeginForm())
{
<ul>
@for (int i = 0; i < Model.Length; i++)
{
<li>
@Html.CheckBoxFor(m => m[i].IsChecked)
@Html.DropDownListFor(m => m[i].SelectedValue, Model[i].Items)
</li>
}
</ul>
<input type="submit" value="Save"/>
}
而且控制器:
[HttpGet]
public ActionResult Index()
{
return View(new CheckedListModel[]
{
//Sample data
new CheckedListModel{Items = new SelectList(new []
{
new SelectListItem{Text = "Text 1", Value="1"},
new SelectListItem{Text = "Text 2", Value="2"},
new SelectListItem{Text = "Text 3", Value="3"},
}, "Value", "Text")},
new CheckedListModel{Items = new SelectList(new []
{
new SelectListItem{Text = "Text 5", Value="5"},
new SelectListItem{Text = "Text 6", Value="6"},
}, "Value", "Text")},
});
}
[HttpPost]
public ActionResult Index(CheckedListModel[] models)
{
IEnumerable<CheckedListModel> checkedItems = models.Where(m => m.IsChecked);
//Rest of the code
}