Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc @Html.CheckBoxFor

I have checkboxes in my form
enter image description here

I added at my model

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

but I get the mistake
enter image description here

What's wrong?

like image 599
Heidel Avatar asked May 22 '13 09:05

Heidel


People also ask

How do I use CheckBoxFor in HTML?

CheckBoxFor(m => m. SomeBooleanProperty, new { @checked = "checked" }); The first parameter must identify a boolean property within your model (it's an Expression not an anonymous method returning a value) and second property defines any additional HTML element attributes.

How can get checkbox value in ASP NET MVC?

Just add value="true" to the input tag. And use a hidden with value="false" as shown below.


2 Answers

Html.CheckBoxFor expects a Func<TModel, bool> as the first parameter. Therefore your lambda must return a bool, you are currently returning an instance of List<Checkboxes>:

model => model.EmploymentType

You need to iterate over the List<Checkboxes> to output each checkbox:

@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) })
}
like image 21
Oliver Avatar answered Sep 21 '22 06:09

Oliver


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);
}
like image 122
mattytommo Avatar answered Sep 20 '22 06:09

mattytommo