'object' does not contain a definition for

2019-09-14 01:40发布

问题:

I have created a ExistingUsers controller in MVC :

    public ActionResult ExistingUsers()
    {
        MembershipUserCollection users = Membership.GetAllUsers();

        return View(users);
    }

And the following view for the above controller:

@model MembershipUserCollection

@{
    ViewBag.Title = "ExistingUsers";
}

<h2>ExistingUsers</h2>

<table>
    <tr>
        <th>
            Username
        </th>
        <th>
            CreationDate
        </th>
        <th>
            Email
        </th>
        <th>
        </th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.UserName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CreationDate)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Email)
            </td>
            <td>
                <a href="/Account/DeleteUser?UserName=@item.UserName">Delete</a>
            </td>
        </tr>
        }
    }
</table>

But whenever i send a request to the controller, an exception occur says :

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: 'object' does not contain a definition for 'UserName' and no extension method 'UserName' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

Source Error:


Line 25:         <tr>
Line 26:             <td>
Line 27:                 @Html.DisplayFor(modelItem => item.UserName)
Line 28:             </td>
Line 29:             <td>

Whats going wrong here ?

回答1:

It may be that you need to explicitly specify the type for the items in the 'for' loop - try:

@foreach (MembershipUser item in Model)