4

私はUsersClassを持っていますが、これは10個を超えるアイテムを持つことはありません。このようなビューでユーザークラスをテーブルで表示するにはどうすればよいですか?

10個のセルで2行を表示したい

4

2 に答える 2

10

いつものように、すべてのASP.NET MVCアプリケーションで、ビューの要件に適合したビューモデルを使用することをお勧めします。したがって、このビューでは、これらのユーザーを1行あたり5つの要素でグループ化するテーブルについて言及しました。

public class MyViewModel
{
    public int Key { get; set; }
    public IEnumerable<UsersClass> Users { get; set; }
}

次に、コントローラーアクションで:

public ActionResult Index()
{
    // that's your domain model => a list of UsersClass
    // could be coming from wherever you want
    var users = Enumerable.Range(1, 7).Select(x => new UsersClass
    {
        Id = x
    });

    // Now let's group those users into the view model:
    // We will have 5 elements per row
    var model = users
        .Select((u, index) => new { User = u, Index = index })
        .GroupBy(x => x.Index / 5)
        .Select(x => new MyViewModel
        {
            Key = x.Key,
            Users = x.Select(y => y.User)
        });
    return View(model);
}

そして最後に、強く型付けされたビューは非常に簡単です。

@model IEnumerable<MyViewModel>
<table>
    @foreach (var item in Model)
    {
        <tr>
            @foreach (var user in item.Users)
            {
                <td>@user.Id</td>
            }

            <!-- That's just to fill the row with the remaining
                 td if we have less than 5 users. Obviously
                 depending on your requirements you could use
                 a single td with a calculated colspan or something else
            -->
            @for (int i = item.Users.Count(); i < 5; i++)
            {
                <td></td>
            }
        </tr>
    }
</table>

明らかに、このビューは、表示テンプレートを使用してさらに簡略化できます。

@model IEnumerable<MyViewModel>
<table>
    @Html.DisplayForModel()
</table>

および対応する表示テンプレート:

@model MyViewModel
<tr>
    @Html.DisplayFor(x => x.Users)
    @for (int i = item.Users.Count(); i < 5; i++)
    {
        <td></td>
    }
</tr>

およびUsersClass表示テンプレート:

@model UsersClass
<td>@user.Id</td>

そして結果:

ここに画像の説明を入力してください

于 2012-05-08T13:15:51.533 に答える
3

これがあなたが探しているものであるかどうかはわかりませんが、正確でない場合は、簡単に変更できるはずです。

@* Check to make sure your user class is not null *@
@if (Model.UserClass != null)
{
    <table>
    for (int i = 1; i <= 2; i++)
    {
        <tr>
        for (int j = 1; j <= 5; j++)
        {
            <td>if (Model.UserClass[(j*i)-1] != null) { Model.UserClass[(j*i)-1] }</td>
        }
        </tr>
    }
    </table>
}

私はこれをかなり早く書きましたが、これはあなたが必要とするものに近いはずです。

于 2012-05-08T13:21:19.847 に答える