【发布时间】:2019-02-19 09:38:59
【问题描述】:
基本上,我有一个类有很多我想绑定到视图的属性。每次打字都非常痛苦且难以维护,所以想知道是否有更简单的方法。
当前型号:
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: 最终,我根据 Soufiane Tahiri 的回答想出了一些愚蠢的 hacky 方法。
@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)
}
【问题讨论】:
-
模型中有名称和布尔值的字典。循环它以创建复选框。
-
@Reniuz 但是这样做不会将复选框与模型绑定吗?
-
您是否尝试过使用
@Html.EditorForModel()? -
我不确定,但others tried it.
标签: c#