2012-05-11 28 views
1

我在我的VIEW中有以下代碼,此後有一個提交按鈕。在我看來,我確實有很多這些複選框,以便用戶可以根據自己的意願點擊。複選框的值使用htmlhelpers返回給控制器

@Html.CheckBox("code" + l_code, false, new { Value = @item.expertiseCode }) 

在我的控制器我有FLL,這是HTTPPost方法

public ActionResult RegisterSP(RegisterModel model, FormCollection collection) 

然而,在調試時,我看到所有的複選框被傳遞迴控制器,而不是隻那些被點擊的人。我只想要那些被點擊並忽略剩下的,因爲我需要將這些添加到數據庫中。另外,傳入的checbox值包含TRUE/FALSE。正因爲如此,虛假的價值也被添加到數據庫中。如果我使用下面的方法(不使用htmlHelper),我沒有上述問題。但我WUD喜歡使用的HtmlHelper:

<input type="checkbox" name="[email protected](l_code)" value="@item.expertiseCode" /> 
+0

H ow是你創建的複選框? –

回答

0

嘗試

@Html.CheckBox("code" + l_code, false, new { @value = item.expertiseCode }) 

string name = "code" + l_code; 
@Html.CheckBox(name, false, new { @value = item.expertiseCode }) 
1

,如果你有複選框的集合,創建一個視圖模型這樣

public class ExpertiseCodeViewModel 
{ 
    public string Name { set;get;} 
    public int ExpertiseId { set;get;} 
    public bool IsSelected { set;get;} 
} 

現在在你的主視圖模型中,添加一個這個集合作爲一個屬性

public class UserViewModel 
{ 
    public List<ExpertiseCodeViewModel > Expertises{ set; get; } 

    public UserViewModel() 
    { 
    if(this.Expertises==null) 
     this.Expertises=new List<ExpertiseCodeViewModel>(); 
    } 
} 

而在你在你的主視圖

@model UserViewModel 
@using (Html.BeginForm()) 
{ 
    //other elements 
@Html.EditorFor(m=>m.Expertises) 
<input type="submit" value="Save" /> 
} 

創建一個名爲ExpertiseCodeViewModel

@model ExpertiseCodeViewModel 
@Html.CheckBoxFor(x => x.IsSelected) 
@Html.LabelFor(x => x.IsSelected, Model.Name) 
@Html.HiddenFor(x => x.ExpertiseId) 

編輯模板包含這在你HTTPPost操作方法,

[HttpPost] 
public ActionResult Save(UserViewModel model) 
{ 
    List<int> items=new List<int>(); 
    foreach (ExpertiseCodeViewModel objItem in model.Expertises) 
    { 
    if (objPVM.IsSelected) 
    { 
     //you can get the selected item id here 
     items.Add(objItem.ExpertiseId); 

    } 
    } 
}