我有一个宿舍添加页面,这个宿舍可以有功能,所以我想使用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; }
}
我可以在剃须刀中获取功能列表作为复选框 但我无法选中复选框ID列表(因此,FeatureID)
如何在控制器中获取列表?
答案 0 :(得分:1)
首先,添加一个将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; }
}
在Razor标记中,将复选框绑定到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属性,即Checked
集合中的DormOptions
属性。
[HttpPost]
public ActionResult CreateDorm(CreateDormViewModel postData) {
var selectedFeatureIds = new List<int>();
foreach (var option in postData.DormOptions) {
if (option.Checked) {
selectedFeatureIds.Add(option.FeatureID);
}
}
// ...
}
答案 1 :(得分:-1)
您可以使用复选框的名称来获取列表,假设您的复选框名称为chklstfeatureid,然后在控制器中您可以获得如下所示的列表
import Foundation
var str = UUID(uuidString: "Hello World")
print(str.uuidString)
由于