Reputation: 2308
I am trying to understand why I get an exception when I try to get elements from a string array containing roles for my application.
error: Object reference not set to an instance of an object. (ViewBag.roles)
Here is how I am getting the roles:
public ActionResult AdminRolesAndAccessRules()
{
String[] rolesArray;
rolesArray = Roles.GetAllRoles();
ViewBag.roles = rolesArray;
return PartialView();
}
and here is how I am using the information:
<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>
Debugging I can see 2 values in ViewBag.roles
but still the system complaining about a Null or not instantiated object.
Upvotes: 2
Views: 5047
Reputation: 54368
// 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.
Those 2 values are presumably the roles you assigned.
// 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>
}
Upvotes: 1