Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为大型号设置/绑定HtmlHelper.CheckBoxFor的更快/更方便/高效方法_C# - Fatal编程技术网

C# 为大型号设置/绑定HtmlHelper.CheckBoxFor的更快/更方便/高效方法

C# 为大型号设置/绑定HtmlHelper.CheckBoxFor的更快/更方便/高效方法,c#,C#,基本上,我有一个类,它有许多属性要绑定到视图。每次输入一个都很痛苦,很难维护,所以我想知道是否有更简单的方法 当前型号: 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 {

基本上,我有一个类,它有许多属性要绑定到视图。每次输入一个都很痛苦,很难维护,所以我想知道是否有更简单的方法

当前型号:

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; } 

}
电流控制器:

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

}
当前视图:

@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)
风景部分对我来说是可怕的

编辑: 变量名就是一个例子

编辑2: 最后,我根据苏菲安·塔希里的答案想出了一些愚蠢的方法

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

可以通过模型属性使用反射和循环:

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

工作片段:

在模型中有一个名称和布尔值的字典。循环创建复选框。@Reniuz但这样做不会使复选框与模型绑定吗?您是否尝试过使用
@Html.EditorForModel()
?我不确定,但是。这是我的直觉,但不幸的是,这样做,视图将不会与模型绑定。如果不绑定,问题可能是其他问题