簡體   English   中英

asp.net mvc 3 razor & html table

[英]asp.net mvc 3 razor & html table

我有 UsersClass,它永遠不會超過 10 個項目。 如何在視圖中顯示帶有表格的用戶類?

我想顯示兩行 10 個單元格

一如既往,在每個 ASP.NET MVC 應用程序中,我建議使用適合視圖要求的視圖模型。 因此,在此視圖中,您提到了一個表,您希望在其中按每行 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>

結果:

在此處輸入圖片說明

不確定這是否正是您要查找的內容,但如果不准確,您應該能夠輕松修改它:

@* 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>
}

我寫得很快,但這應該接近你所需要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM