在MVC实体控制器中生成视图代码(如下)。我正在关注的教程的作者想要添加HTML帮助器,它可以删除超过25个字符的艺术家姓名。
然后他以这种方式使用那个助手:@Truncate(item.Artist.Name, 25)
。
为什么最初使用DisplayFor(modelItem => item.Artist.Name)
而不是item.Artist.Name
?
@helper Truncate(string input, int length) {
if (input.Length <= length) {
@input
} else {
@input.Substring(0, length)<text>...</text>
}
}
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Genre.Name)
</td>
<td>
@Truncate(item.Artist.Name, 25)
</td>
<td>
@Truncate(item.Title, 25)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.AlbumId }) |
@Html.ActionLink("Details", "Details", new { id = item.AlbumId }) |
@Html.ActionLink("Delete", "Delete", new { id = item.AlbumId })
</td>
</tr>
}