4

Basically, I have a class that has many properties that I want to bind to the View. Typing one by the time is quite painful and hard to maintain, so was wondering if there was an easier way of doing so.

Current Model:

public class test
{
    public bool a { get; set; } 
    public bool b { get; set; } 
    public bool c { get; set; } 
    .
    .
    .
    public bool x { get; set; } 
    public bool y { get; set; } 
    public bool z { get; set; } 

}

Current Controller:

public ActionResult checkbox()
{
    var viewModel = new test();
    return View(viewModel);

}

Current View:

@model Test.Program.test

@Html.CheckBoxFor(m => m.a)
@Html.LabelFor(m => m.a)

@Html.CheckBoxFor(m => m.b)
@Html.LabelFor(m => m.b)

@Html.CheckBoxFor(m => m.c)
@Html.LabelFor(m => m.c)
.
.
.
@Html.CheckBoxFor(m => m.x)
@Html.LabelFor(m => m.x)

@Html.CheckBoxFor(m => m.y)
@Html.LabelFor(m => m.y)

@Html.CheckBoxFor(m => m.z)
@Html.LabelFor(m => m.z)

The View part is the part that is horrifying to me.

Edit: Variable names are just for example.

Edit2: Eventually, I came up with some stupid hacky way based on Soufiane Tahiri answer.

@foreach (var prop in test.GetType().GetProperties())
    {
        //here by adding the model in front will cause the model to bind with the response
        @Html.CheckBox("test." + prop.Name)
        @Html.Label(prop.Name)
    }
Michael
  • 395
  • 1
  • 13

1 Answers1

3

You can use reflexion and loop through your model properties:

    @foreach (PropertyInfo prop in Model.GetType().GetProperties())
    {
     @Html.CheckBox(prop.Name)
     @Html.Label(prop.Name)
    }

A working snippet: https://dotnetfiddle.net/4hiOZr

Soufiane Tahiri
  • 171
  • 1
  • 15