2013-05-22 33 views
16

我在我的形式複選框
enter image description hereasp.net的MVC @ Html.CheckBoxFor

我在模型

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 

namespace CorePartners_Site2.Models 
{ 
public class CareerForm 
    { 
    //.... 
    public List<CheckBoxes> EmploymentType { get; set; } 
     } 
} 

public class CheckBoxes 
{ 
    public string Text { get; set; } 
    public bool Checked { get; set; } 
} 

並在我的形式加入

@Html.CheckBoxFor(model => model.EmploymentType, new { id = "employmentType_1" }) 
@Html.CheckBoxFor(model => model.EmploymentType, new { id = "employmentType_2" }) 
@Html.CheckBoxFor(model => model.EmploymentType, new { id = "employmentType_3" }) 

,但我得到錯誤
enter image description here

有什麼不對?

回答

33

CheckBoxFor需要bool,您將List<CheckBoxes>傳遞給它。你需要做的事:

@for (int i = 0; i < Model.EmploymentType.Count; i++) 
{ 
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "employmentType_" + i }) 
    @Html.HiddenFor(m => m.EmploymentType[i].Text) 
    @Html.DisplayFor(m => m.EmploymentType[i].Text) 
} 

通知我添加了Text財產太一HiddenFor,否則你會失去,當你張貼的形式,這樣你就不會知道哪些項目你會檢查。

編輯,如您的評論中所示,您的EmploymentType列表爲null。你需要來填充過,在你的操作方法這樣做:

public ActionResult YourActionMethod() 
{ 
    CareerForm model = new CareerForm(); 

    model.EmploymentType = new List<CheckBox> 
    { 
     new CheckBox { Text = "Fulltime" }, 
     new CheckBox { Text = "Partly" }, 
     new CheckBox { Text = "Contract" } 
    }; 

    return View(model); 
} 
+0

我需要我的窗體中添加該代碼? – Heidel

+0

@海德爾呀在你的表格 – mattytommo

+0

我試過了,但是我得到了這個[http://i.imgur.com/Q78xcBD.png](http://i.imgur.com/Q78xcBD.png)。怎麼了? – Heidel

1

使用此代碼:

@for (int i = 0; i < Model.EmploymentType.Count; i++) 
{ 
    @Html.HiddenFor(m => m.EmploymentType[i].Text) 
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "YourId" }) 
} 
4

Html.CheckBoxFor需要一個Func<TModel, bool>作爲第一個參數。因此,你的拉姆達必須返回一個bool,目前你正在返回的List<Checkboxes>一個實例:

model => model.EmploymentType 

,需要在每個複選框遍歷List<Checkboxes>輸出:

@for (int i = 0; i < Model.EmploymentType.Count; i++) 
{ 
    @Html.HiddenFor(m => m.EmploymentType[i].Text) 
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, 
       new { id = string.Format("employmentType_{0}", i) }) 
} 
2

如果只有一個複選框應檢查在同一時間使用RadioButtonFor代替:

 @Html.RadioButtonFor(model => model.Type,1, new { @checked = "checked" }) fultime 
     @Html.RadioButtonFor(model => model.Type,2) party 
     @Html.RadioButtonFor(model => model.Type,3) next option... 

如果多一個可以在同一時間檢查使用exc ellent擴展:CheckBoxListFor

希望,這將有助於

+1

不,謝謝你,但我不需要這裏的RadioButton – Heidel