【问题标题】:How to use If mode statement correctly inside Html code如何在 Html 代码中正确使用 If 模式语句
【发布时间】:2015-01-07 08:16:27
【问题描述】:

我有一个包含 9 张图片的“td”,我想将它们分成 3×3。所以我想得到这样的视图:

  • Pic1 Pic2 Pic3
  • Pic4 Pic5 Pic6
  • Pic7 Pic8 Pic9

这是我的查看代码。

@for (int k = 0; k < Model.Count; k++)
  {
  <td>
  <img src="(Model[k].Pic)" width="80" height="90" />
  </td>
  }

我正在尝试通过此代码拆分图片:

@for (int k = 0; k < Model.Count; k++)
{
 <td>

 <div>
  <img src="(Model[k].Pic)" width="80" height="90" />

  </div>   
 @if (k % 3 == 0)
{
     @:<div></div>
}

     </td>
  }                                             

但是我不能分割图片。这是一个简单的代码,但我失败了。问题出在哪里?

【问题讨论】:

    标签: html asp.net-mvc


    【解决方案1】:

    您可以创建一个 LINQ 方法来创建具有指定大小的分区:

    public static class PartitionExtensions
    {
        private static IEnumerable<IEnumerable<T>> ToSizedPartition<T>(IEnumerable<T> source, int size)
        {
            int currentPartitionCount = 0;
            T[] array = null;
    
            foreach (T item in source)
            {
                if (array == null)
                {
                    array = new T[size];
                }
    
                array[currentPartitionCount] = item;
                currentPartitionCount++;
    
                if (currentPartitionCount == size)
                {
                    yield return array;
                    currentPartitionCount = 0;
                    array = null;
                }
            }
    
            if (array != null)
            {
                Array.Resize(ref array, currentPartitionCount);
                yield return array;
            }
        }
    }
    

    然后改变你的看法:

    <td>
        @foreach (var partition in Model.ToSizedPartition(3))
        {
             <div>
                 @foreach(var item in partition)
                 {
                     <img src="@item.Pic" width="80" height="90" />
                 }
             </div>
        }
    </td>
    

    【讨论】:

    • 感谢您的回答。作为一个 MVC 菜鸟,对我来说很难实现。
    • @ispanak 这并不难。只需将 PartitionExtensions 类添加到您的项目中。
    • 如何将 ToSizedPartition 与我的模型绑定?我不知道如何实现它。我只有一个简单的模型,它有 3-4 个属性,其中一个是 Foto 属性。
    • @ispanak 这是一个通用的extension method。您不必为您的类型实现它。
    【解决方案2】:

    你可以像下面提到的那样简单地使用:

    <table>
        <tr>
            <td>
                @for (int k = 0; k < Model.Count; k++)
                {
                    if (k % 3 == 0 && k != 0)
                    {
                        <div style="clear: both"></div>
                    }
                    <div style="float: left">
                        <img src="@Model[k].Pic" width="80" height="90" />
                    </div>
                }
            </td>
        </tr>
    </table>
    

    【讨论】:

    • 感谢您的回复。我没有得到我想要的结果。
    • 你得到了什么结果?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多