1

我想知道如何从以下模型中获取值并显示复选框列表,并选中相应的复选框。为简单起见简化了模型。

模型_

 public class Project
 {
    public int ProjectID { get; set; }
    public string Title { get; set; }
    public virtual ICollection<Characteristic> Characteristic { get; set; }
 }
 public class Characteristic
 {
    public int CharacteristicID { get; set; }
    public string CharacteristicName { get; set; }

    public virtual ICollection<Project> Project { get; set; }
 }
 public class ProjectCharacteristic
 {
    public int ID { get; set; }
    public int ProjectID { get; set; }
    public int CharacteristicID { get; set; }

    public Project Project { get; set; }
    public Characteristic Characteristic { get; set; }
 }

视图模型

public class ProjectEditIndexData
{
    public Project Project{ get; set; }
    public List<Characteristic> Chars { get; set; }
}

控制器_

 public ActionResult Edit(int id = 0)
    {
        ProjectEditIndexData project = new ProjectEditIndexData();
        project.Project = db.Projects.Find(id);
        project.Chars = db.Characteristics.ToList();
        return View(project);
    }

重申: 如何将项目中所有给定特征的列表作为复选框,其中已选中的特征标记为已选中?

4

1 回答 1

2

我无法让助手工作,所以我只是编写了一个 foreach 循环来检查查找表中是否存在该值并将其标记为我自己检查。我在 Razor 视图中执行此操作。有用。不确定这是否是不好的做法。

       foreach(var c in Model.Chars) {
            string checkedStatus = "";
            if (Model.Project.ProjectCharacteristic.Any(x => x.CharacteristicID == c.CharacteristicID))
            {
                checkedStatus = "checked";
            }
            <label class="label_check">
                <input type="checkbox" name="Characteristic" value="@c.CharacteristicID" @checkedStatus> @c.CharacteristicName
            </label>
        }
于 2013-01-04T04:46:26.110 回答