Jed Grant
Jed Grant

Reputation: 1425

MVC 4 Razor Html.Checkbox List from Many to Many Relationship

I want to know how to take values from the following model and display a list of checkboxes, with the appropriate checkboxes checked. Models simplified for simplicity.

The Models

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

The ViewModel

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

The Controller

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

To Restate: How do I get a list of all of the given characteristics on the project as checkboxes with those that are already selected marked as checked?

Upvotes: 1

Views: 4284

Answers (1)

Jed Grant
Jed Grant

Reputation: 1425

I wasn't able to get the helper to work, so instead I just wrote a foreach loop that checked to see if the value existed in the lookup table and marked it as checked myself. I did this in the Razor view. It works. Not sure if it's bad practice though.

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

Upvotes: 2

Related Questions