我的表格中有复选框

我在模型上加了

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

但是我弄错了

怎么了?

最佳答案

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,否则在发布表单时您会丢失该信息,因此您将不知道要检查哪些项目。

如评论中所示,在提供 View 时,编辑EmploymentType列表为null。您还需要通过在action方法中执行以下操作来填充它:
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);
}

关于c# - asp.net mvc @ Html.CheckBoxFor,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16688170/

10-10 11:30