当我访问ViewBag对象时,对象引用未设置为对象的实例

时间:2012-11-21 00:52:02

标签: asp.net-mvc asp.net-mvc-4 exception

我试图理解为什么在尝试从包含我的应用程序角色的字符串数组中获取元素时会出现异常。

  

错误:对象引用未设置为对象的实例。   (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/DeleteUser?role=@muc", "POST", "DinamicContent", "AdminSettingsTabsStructure")'><img src="~/Images/excluir.gif" alt="Excluir"/></a>
        </td> 
    </tr>

    }     
    </table>

调试我可以在ViewBag.roles中看到2个值,但系统仍抱怨Null或未实例化的对象。

1 个答案:

答案 0 :(得分:1)

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

Debbugging我可以在ViewBag.rules中看到2个值,但仍然是系统   抱怨Null或没有实例化的对象。

这两个值可能是您指定的角色。

// 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>
}