2012-11-21 55 views
2

我想了解爲什麼當我嘗試從包含我的應用程序的角色的字符串數組中獲取元素時出現異常。當我foreach ViewBag對象時,對象引用未設置爲對象的實例

error: Object reference not set to an instance of an object. (ViewBag.roles)

這裏是我如何得到角色:

public ActionResult AdminRolesAndAccessRules() 
    { 
     String[] rolesArray; 
     rolesArray = Roles.GetAllRoles(); 

     ViewBag.roles = rolesArray; 

     return PartialView(); 
    } 

這裏我如何使用的信息:

<div class="scroller"> 
    <table> 
     @foreach (MembershipUserCollection muc in ViewBag.roles) 
    {           
     if(column == 1) { 
      classe = "whiteRow"; 
      column = 0; 
     } 
     else { 
      classe = "grayRow"; 
      column = 1; 
     } 
    <tr class="@classe"> 
     <td class="adminSetFormRowUsuario">role</td> 
     <td class="adminSetFormRowGrupo"></td> 
     <td class="formAction centerAlign"> 
      <img src="~/Images/editar.gif" alt="Editar"/> 
      <span style="margin-left:5px"></span> 
      <a href='javascript:AjaxRemoveUser("/Account/[email protected]", "POST", "DinamicContent", "AdminSettingsTabsStructure")'><img src="~/Images/excluir.gif" alt="Excluir"/></a> 
     </td> 
    </tr> 

    }  
    </table> 

調試我可以看到ViewBag.roles但仍2個值系統抱怨一個空或者沒有實例化的對象。

+0

它看起來就像你分配一個字符串數組來ViewBag.Roles,但隨後通過這些字符串迭代爲不同類型('MembershipUserCollection') –

回答

1
// string array being assigned here 
String[] rolesArray = Roles.GetAllRoles(); 
ViewBag.roles = rolesArray; 

Debbugging I can see 2 values in ViewBag.rules but still the system complaining about a Null or not instatiated object.

這2個值大概是你賦予的角色。

// This looks wrong...you are treating each string in the array as MembershipUserCollection 
@foreach (MembershipUserCollection muc in ViewBag.roles) 
{ 
} 

// instead, this should give you the role names 
@foreach(string role in ViewBag.roles) 
{ 
    <div>@role</div> 
} 
+0

我想,也能在第一時間。也沒有工作!我也將控制器更改爲string []而不是String []。 –

+0

你有沒有試過只寫出角色名稱逐字(我剛更新我的例子)? –

+0

是的。 @ role。當代碼在foreach內部的ViewBag.roles之上時,異常發生了。它沒有進入功能。 –

相關問題