【问题标题】:Object reference not set to an instance of an object when I foreach ViewBag object当我 foreach ViewBag 对象时,对象引用未设置为对象的实例
【发布时间】:2012-11-09 04:48:25
【问题描述】:

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

错误:对象引用未设置为对象的实例。 (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 或未实例化对象。

【问题讨论】:

  • 看起来您正在为 ViewBag.Roles 分配一个字符串数组,但随后将这些字符串作为不同的类型进行迭代 (MembershipUserCollection)

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


【解决方案1】:
// string array being assigned here
String[] rolesArray = Roles.GetAllRoles();
ViewBag.roles = rolesArray;

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

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

【讨论】:

  • 我第一次也试过了。也没有工作!我还将控制器更改为 string[] 而不是 String[]。
  • 您是否尝试过逐字逐句写出角色名称(我刚刚更新了我的示例)?
  • 是的.. @role。当代码正好位于 foreach 内的 ViewBag.roles 之上时,就会发生异常。它不会进入函数内部。
  • 感谢您的关注。我真的为自己的错误感到羞耻。我正在使用一个 jquery 选项卡结构,我在其中加载不同的视图,并且这个特定的视图是在创建对象之前构建的,因此是一个空引用。问题解决了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多