类ASP.NET MVC中的struct数组初始化

时间:2015-06-16 13:49:20

标签: c# asp.net arrays asp.net-mvc

我在类数组中初始化数组时遇到问题,我有一个SearchArrayModel:

public class SearchArrayModel
{
    public struct AttribStruct
    {
        public string AttribName { get; set; }
        public string[] AttribValues { get; set; }
    }
    public AttribStruct[] AttribArray { get; set; }
}

我有一个控制器来填充数组:

SearchArrayModel[] src = new SearchArrayModel[1]
{
    new SearchArrayModel()
    {
        AttribArray = new SearchArrayModel.AttribStruct[]
        {
            new SearchArrayModel.AttribStruct
            {
                AttribName = atributes2.attribname, //it's in foreach loop, but it's a string value
                AttribValues = new string[] 
                {
                    values.ToString() //another string values
                }
            }
        }
    }
}

我的观点:

@model allegrotest.Models.SearchArrayModel
@{
    ViewBag.Title = "ShowItems";
}

@using (Html.BeginForm())
{
    @foreach (var item in Model.AttribArray)
    {
        foreach (var item2 in item.AttribName)
        {
            <h2>@item2</h2>
        }
    }
}

这是对的吗?我想显示AttribArray中的所有元素,但在我的视图中我只有一个元素

或者我的foreach循环可能有错误。

2 个答案:

答案 0 :(得分:1)

如果AttribValues = values.Select(v => v.ToString()).ToArray() //another string values 是您可能想要的集合

{{1}}

答案 1 :(得分:1)

您无法迭代string值。要显示数组中的所有元素,您可以将代码重新排列为:

@model allegrotest.Models.SearchArrayModel
@{
    ViewBag.Title = "ShowItems";
}

@using (Html.BeginForm())
{
   @foreach (var item in Model.AttribArray)
   {
      <h2>@item.AttribName</h2>
      foreach (var item2 in item.AttribValues)
      {
         <h3>@item2</h3>
      }
   }
}