Question

I am developing an ASP.Net MVC 3 Web application using Entity Framework 4.1. I am having trouble displaying a CheckBoxList. Let me explain.

I have two ViewModel's

public class ViewModelShiftSubSpecialties
{
    public IEnumerable<ViewModelCheckBox> SpecialtyList { get; set; }
}

public class ViewModelCheckBox
{
    public string Id { get; set; }
    public string Name { get; set; }
    public bool Checked { get; set; }
    public string Specialty { get; set; }
}

In my Controller, I populate my ViewModels

        IList<RelationshipGradeSub> gradeSubSpecialties = GetSubSpecialtiesForGrade(firstShiftGrade.gradeID);

        ViewModelShiftSubSpecialties viewModel = new ViewModelShiftSubSpecialties();

        var checkBoxList = new List<ViewModelCheckBox>();

        foreach (var item in gradeSubSpecialties)
        {
            ViewModelCheckBox chkBox = new ViewModelCheckBox { Id = item.subID.ToString(), Name = item.ListSubSpecialty.description, Checked = false, Specialty=item.ListSubSpecialty.ListItemParent.description };
            checkBoxList.Add(chkBox);
        }

        viewModel.SpecialtyList = checkBoxList;

        return View(viewModel);

I also have a partial view which is used as an EditorTemplate to display my checkboxes

@Html.HiddenFor(x => x.Id)        
@Html.CheckBoxFor(x => x.Checked)
@Html.LabelFor(x => x.Name, Model.Name)<br />

Then in my View I try to filter through Model.Specialty and categorise the items into three checkboxlists based on their Specialty, ie:

@foreach (var sub in Model.SpecialtyList)
{
if (sub.Specialty.Equals("Medicine"))
{
    @Html.EditorFor(m => m.SpecialtyList)
}
else if (sub.Specialty.Equals("Surgery"))
{
    @Html.EditorFor(m => m.SpecialtyList)
}
else if (sub.Specialty.Equals("Pathology"))
{
    @Html.EditorFor(m => m.SpecialtyList)
}

}

But this doesn't seem to be working at all, what this gives me is nothing in the 1st or 2nd checkboxlist, and then all list items in the 3rd checkboxlist. Basically what I am trying to achieve is something like this

enter image description here

Could someone please give me some pointers to get this working?

Thanks.

Was it helpful?

Solution

I guess your EditorTemplate for displaying a checkbox is for type ViewModelCheckBox:

@Html.HiddenFor(x => x.Id)        
@Html.CheckBoxFor(x => x.Checked)
@Html.LabelFor(x => x.Name, Model.Name)<br />

In that case, you're sending in List<ViewModelCheckBox> when using @Html.EditorFor(m => m.SpecialtyList), but what you should send in is ViewModelCheckBox:

@Html.EditorFor(m => sub)

I hope I understood you correctly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top