如何使用组合Property扩展ViewModel

时间:2015-04-28 08:38:40

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-5 asp.net-mvc-viewmodel

在一个MVC项目中,我使用了这个简单的ViewModel来填充.cshtml中的表。每个列都可以使用设备对象中的属性轻松填充。

我需要创建一个新列并用计数填充它。此计数是从服务器上的deviceId制作的。

我想用Count属性扩展我的ViewModel。计数由每个用于检索列表然后计数的deviceId制作。

所以我的问题是你如何设计这个"撰写"视图模型?我想把它全部包装在私人课堂中,但我不知道这是不是最好的做法。

视图模型:

public class DeviceViewModel
{
    public List<Device> Devices { get; set; }
}

.cshtml:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Priority</th>
            <th>Version</th>
        </tr>
    </thead>

    <tbody>
    @{
        foreach (var device in Model.Devices)
        {
            <tr id="@device.ID">
                <td>@device.Name</td>
                <td>@device.Priority</td>
                <td>@device.Version</td>
            </tr>
        }
    }
    </tbody>
</table>

我认为.cshtml是这样的,并且不了解ViewModel:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Priority</th>
            <th>Version</th>
            <th>Count</th>
        </tr>
    </thead>

    <tbody>
    @{
        foreach (var composedDevice in Model.ComposedDevices)
        {
            <tr id="@composedDevice.ID">
                <td>@composedDevice.Name</td>
                <td>@composedDevice.Priority</td>
                <td>@composedDevice.Version</td>
                <td>@composedDevice.Count</td>
            </tr>
        }
    }
    </tbody>
</table>

0 个答案:

没有答案