Search code examples
c#asp.net-mvc-4mvc-editor-templatesasp.net-mvc-viewmodel

How to Create MVC4 checkbox list with descriptions/values generated at run time


I want to create a form that shows a number of checkbox lists along with some other fields, where the values and text of those lists is determined at run time.

I've run into a situation where I can get the bool property of the model to update, but the other properties get nulled out once the form is posted.

I'm sure there's a simple solution, but I can't seem to find it.

public class MainModel 
{
  public List<CheckboxModel> Checkboxes { get; set;}
  public MainModel() 
  {
    this.Checkboxes = InitializeMethod(); // populates both description and selected for a bunch of boxes.
  }
}

public class CheckboxModel
{
  public String Description { get; set; } // This field is null when I get the model back in the HttpPost request
  public bool Selected { get; set; }
}

Main Form View

@model MainModel
@{
  for(var i = 0; i < Model.Checkboxes.Count; i++) 
  {
    @Html.EditorFor(m => m.Checkboxes[i]);
  }
}

CheckboxModel editor view

@model CheckboxModel

@Html.CheckBoxFor(m => m.Selected)
@Html.DisplayFor(m => m.Description)<br/>

Solution

  • Your not generating a form control for the Description property so no value is sent in the form data when you post. Your template should be, for example

    @model CheckboxModel
    
    @Html.CheckBoxFor(m => m.Selected)
    @Html.DisplayFor(m => m.Description)
    @Html.HiddenFor(m => m.Description)
    

    or use a readonly textbox to display the Description

    Side note: Your main view should be just

    @Html.EditorFor(m => m.Checkboxes)
    

    without the for loop. The EditorFor() method accepts IEnumerable<T> and generates the correct html for each item in your collection