asp.net mvc @ Html.CheckBoxFor

时间:2013-05-22 09:26:15

标签: c# .net asp.net-mvc asp.net-mvc-4 razor

我的表格中有复选框 enter image description here

我在我的模特中添加了

 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

出了什么问题?

4 个答案:

答案 0 :(得分:37)

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

注意我也为HiddenFor属性添加了Text,否则当您发布表单时会丢失,因此您不会知道要检查哪些项目。< / p>

编辑,如您的评论中所示,在投放视图时,您的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);
}

答案 1 :(得分:3)

Html.CheckBoxFor期望Func<TModel, bool>作为第一个参数。因此,您的lambda必须返回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 :(得分:2)

使用此代码:

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

答案 3 :(得分:1)

如果只应在同一时间选中一个复选框,请使用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...

如果可以同时检查另外一个,请使用优秀的扩展程序:CheckBoxListFor

希望,这会有所帮助