【问题标题】:Quicker/Easier/Efficient way to set/bind HtmlHelper.CheckBoxFor for big model为大型模型设置/绑定 HtmlHelper.CheckBoxFor 的更快/更简单/有效的方法
【发布时间】: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#


【解决方案1】:

您可以使用反射和循环遍历您的模型属性:

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

一个工作的sn-p:https://dotnetfiddle.net/4hiOZr

【讨论】:

  • 这完全是我的直觉,但不幸的是这样做,视图不会与模型绑定。
  • 如果它没有绑定问题可能是别的问题
猜你喜欢
  • 2013-08-22
  • 2015-07-11
  • 1970-01-01
  • 1970-01-01
  • 2018-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多