我有一个宿舍添加页面,这个宿舍可以有功能,所以我想使用CheckBox列表。
有一个宿舍可以拥有的所有功能的列表。
public class DormFeatureModel
{
[Key]
public int FeatureID { get; set; }
public string FeatureName { get; set; }
public List<DormHasFeatureModel> DormHasFeature { get; set; }
}这里也有一些宿舍所具备的功能。
public class DormHasFeatureModel
{
[Key]
public int HasFeatureID { get; set; }
[Required]
public int FeatureID { get; set; }
[Required]
public int DormID { get; set; }
public virtual DormModel Dorm { get; set; }
public virtual DormFeatureModel DormFeature { get; set; }
}我可以在razor中获得功能列表作为复选框,但我无法获得选中的复选框id列表(所以,FeatureID)
如何在控制器中获取列表?
发布于 2017-07-10 23:02:53
首先,添加一个将Checked布尔值与FeatureId关联起来的ViewModel。
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操作创建主ViewModel并初始化可用特性列表(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 lambda中提供的ViewModel属性,即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);
}
}
// ...
}发布于 2017-07-11 10:35:05
你可以通过使用复选框的名称来获得列表,假设你的复选框的名称是chklstfeatureid,那么在控制器中你可以获得如下列表
public actionresult createdorm(list<int> chklstfeatureid)
{
}谢谢
https://stackoverflow.com/questions/45014951
复制相似问题