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()
?我不确定,但是。这是我的直觉,但不幸的是,这样做,视图将不会与模型绑定。如果不绑定,问题可能是其他问题