2017-07-10 25 views
1

我有一個宿舍添加頁面,這個宿舍可以有功能,所以我想使用CheckBox列表。在控制器中獲取選定的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的)

我怎樣才能在控制器獲取列表?

回答

1

首先,添加一個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); 
     } 
    } 
    // ... 
} 
-1

可以使用複選框的名稱,讓說你的複選框的名字chklstfeatureid然後控制器就可以得到這樣的感謝

下面

public actionresult createdorm(list<int> chklstfeatureid) 
{ 

} 

列表獲取列表

相關問題