2012-12-10 160 views
0

我在MVC創建ExistingUsers控制器「用戶名」的定義:「對象」不包含

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

     return View(users); 
    } 

而對於上述控制器的以下觀點:

@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/[email protected]">Delete</a> 
      </td> 
     </tr> 
     } 
    } 
</table> 

但每當我發送一個請求到控制器,發生異常說:

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> 

這是怎麼回事?

+1

聽起來像是'MembershipUserCollection'不公開類型化的枚舉。 – leppie

回答

4

這可能是因爲你需要明確指定爲項目的類型在「for」循環 - 嘗試:

@foreach (MembershipUser item in Model) 
+0

值得注意的是,一旦你這樣做,_IntelliSense_應該建議屬性名稱。如果不這樣做,這種類型可能是問題。我儘量避免使用'var'(隱式類型)。 –