Wednesday, July 20, 2016

asp.net mvc @Html.CheckBoxFor dynamic

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; }
 }
and added at my form
@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 takes a bool, you're passing a List<CheckBoxes> to it. You'd need to do:
@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)
}
Notice I've added a HiddenFor for the Text property too, otherwise you'd lose that when you posted the form, so you wouldn't know which items you'd checked.
Edit, as shown in your comments, your EmploymentType list is null when the view is served. You'll need to populate that too, by doing this in your action method:
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);
}

Set the Reference Path (C#)

To set a reference path

  1. In Solution Explorer, select the project.
  2. On the Project menu, click <Project Name> Properties.
  3. Click Reference Paths.
  4. In the Folder text box, specify the path of the folder that contains assemblies. To browse to the folder, click the ellipsis (…).
  5. Click Add Folder.

To overwrite a reference path

  1. In Solution Explorer, select the project.
  2. On the Project menu, click <Project Name> Properties.
  3. Click Reference Paths.
  4. In the Reference Path box, select the path to overwrite.
  5. In the Folder text box, specify the path of the folder that contains assemblies. To browse to the path, click the ellipsis (…).
  6. Click Update. The path selected in the Reference Path box is overwritten with the path specified in the Folder text box.

To remove a reference path

  1. In Solution Explorer, select the project.
  2. On the Project menu, click <Project Name> Properties.
  3. Click Reference Paths.
  4. In the Reference Path box, select the path to remove.
  5. Click Remove.