首页 > 解决方案 > 在列表中显示列表中的控件信息

问题描述

我正在尝试将所有步骤列表显示为进度条,然后为每个步骤列出下面的所有表单字段。获取步骤列表很容易。我有一个遍历 Steps 列表的 foreach 循环。但是,当我尝试在步骤列表中执行 foreach 时,我收到一条错误消息,指出 Fields Object 为空。

iterates through with no issue but fails at getting the Fields Count:
@foreach (var step in Model.FormAttributes.Steps){
<li>@step.Fields.Count()</li>   }



    {
      "FormName": "Engagement Technology Request Form",
      "FormAttributes": {
      "Steps": [
      {
        "StepNumber": 1,
        "StepName": "Engagement Details",
        "Fields": [
        {
           "type": "text",
           "field-name": "txtBillCode",
           "field-text": "Bill/Matter Code",
           "required": true
         },
      {
        "type": "text",
        "field-name": "txtInformationOwner",
        "field-text": "Information Owner",
        "required": true
      },
      {
        "type": "text",
        "field-name": "txtProjectCode",
        "field-text": "Project Code",
        "required": true
      },
      {
        "type": "text",
        "field-name": "txtDelInformationOwner",
        "field-text": "Delegated Information Owner",
        "required": false
      }
    ]
  },
  {
    "StepNumber": 2,
    "StepName": "Data Details"
  }
]

} }

这就是我正在使用的 json 文件。获取步骤列表很容易。尝试在 foreach 中使用 foreach 来检索每一步的所有字段,我错了吗?

否则如何获取每个步骤的字段列表?任何帮助将不胜感激。

谢谢

标签: jsonasp.net-mvcforeach

解决方案


对于一些Step你没有的Fields,所以你会得到NullReferenceException。您需要添加验证,例如:

@foreach (var step in Model.FormAttributes.Steps)
{
  @if (step.Fields != null && step.Fields.Any())
  {
       <li>@step.Fields.Count()</li>
       @foreach (var field in step.Fields)
       {
        ....
       }
  }
  else
  {
     <li>0</li>
  }
}

推荐阅读