首先,添加一個ViewModel,將Checked
布爾值與FeatureId
相關聯。
public class SelectedFeatureViewModel {
public bool Checked { get; set; } // to be set by user
public int FeatureID { get; set; } // to be populated by GET action
public string FeatureName { get; set; } // to be populated by GET action
}
的GET操作創建主視圖模型和初始化的可用功能(DormOptions
)的列表。
public class CreateDormViewModel {
// used to render the checkboxes, to be initialized in GET controller action
// also used to bind the checked values back to the controller for POST action
public ICollection<SelectedFeatureViewModel> DormOptions { get; set; }
}
在剃刀標記,綁定複選框可以DormOptions
集合:
@model CreateDormViewModel
@using (Html.BeginForm("CreateDorm", "DormAdministration", FormMethod.Post)) {
// use for loop so modelbinding to collection works
@for (var i = 0; i < Model.DormOptions.Count; i++) {
<label>@Model.DormOptions[i].FeatureName</label>
@Html.CheckBoxFor(m => m.DormOptions[i].Checked)
// also post back FeatureId so you can access it in the controller
@Html.HiddenFor(m => m.DormOptions[i].FeatureID)
// post back any additional properties that you need to access in the controller
// or need in order to redraw the view in an error case
@Html.HiddenFor(m => m.DormOptions[i].FeatureName)
}
}
在CreateDorm
POST操作,該複選框值綁定到你的CheckBoxFor
拉姆達,即給視圖模型屬性DormOptions
集合中的Checked
屬性。
[HttpPost]
public ActionResult CreateDorm(CreateDormViewModel postData) {
var selectedFeatureIds = new List<int>();
foreach (var option in postData.DormOptions) {
if (option.Checked) {
selectedFeatureIds.Add(option.FeatureID);
}
}
// ...
}