我试图理解为什么我想在我的模型中访问这样的属性
@Model.Username
它给了我这个错误:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1061: 'System.Collections.Generic.IEnumerable<IntegrateApp.Models.EditUserViewModel>' does not contain a definition for 'Username' and no extension method 'Username' accepting a first argument of type 'System.Collections.Generic.IEnumerable<IntegrateApp.Models.EditUserViewModel>' could be found (are you missing a using directive or an assembly reference?)
但是,如果我这样做的话,它会起作用:
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.MiddleName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Surname)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.UserName }) |
@Html.ActionLink("Details", "Details", new { id = item.UserName }) |
@Html.ActionLink("Delete", "Delete", new { id = item.UserName })
</td>
</tr>
}
答案 0 :(得分:2)
第一个代码段是指视图的Model
属性,该属性是类型IEnumerable<EditUserViewModel>
。 IEnumerable<T>
类是否有Username
属性?不,它没有,因此错误。
第二个代码段使用foreach
循环来枚举IEnumerable<EditUserViewModel>
,因此,在循环内,item
是一个EditUserViewModel
对象和EditUserViewModel
class确实有Username
属性。
归结为模型是一个列表而且列表没有该属性;它是列表中具有该属性的项目。