2017-07-10 19 views
1

私は寮を追加しています。このドミトリーには機能がありますので、このために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

最初に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アクションは、メインビューモデルを作成し、利用可能な機能(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コレクションにチェックボックスをバインド:CreateDorm POSTアクションで

@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) 
    } 
} 

、チェックボックスの値は、あなたがCheckBoxForラムダ、すなわちに与えたの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); 
     } 
    } 
    // ... 
} 
-1

あなたは、チェックボックスのあなたの名前は、コントローラにあなたが

public actionresult createdorm(list<int> chklstfeatureid) 
{ 

} 

以下おかげ

のようなリストを取得することができますchklstfeatureidされるとしましょうチェックボックスの名前を使用して、リストを取得することができます
関連する問題