简体   繁体   中英

ASP.Net MVC ViewBag is not working in View. ViewBag result is Correct

I am having an issue with ViewBag not working in view. The controller returns what i think i need..

On debugging I have Current = false and then on Results View i also have false. The bit is set to false. It seems that all the ViewBag items return False for Current.

When i call the ViewBag in my View it does not seem to do anything. It doesn't fault out either.

Here is my section of code where i am getting current bool info from an array.

 if (GetOrPost == "GET")
 {
    if (actionName == "add" || actionName == "index" || actionName == "create" || actionName == "edit" || actionName == "delete" || actionName == "multiviewindex")
    {
      ViewBag.Add = menuaccess.Where(i => i.MenuURL == controllerName).Select(i => (i.IsAdd));
      ViewBag.Read = menuaccess.Where(i => i.MenuURL == controllerName).Select(i => (i.IsRead));
      ViewBag.Create = menuaccess.Where(i => i.MenuURL == controllerName).Select(i => (i.IsCreate));
      ViewBag.Edit = menuaccess.Where(i => i.MenuURL == controllerName).Select(i => (i.IsUpdate));
      ViewBag.Delete = menuaccess.Where(i => i.MenuURL == controllerName).Select(i => (i.IsDelete));
    }
  }

This is the usage in the view:

  @if (ViewBag.Edit = true)
  {
     @Ajax.ModalDialogActionLink("Edit", "Edit", "Edit User", "btn btn-warning btn-sm", new { UserName = item.UserName })
  }

MenuOfRole brings back every permission for the RoleUser signed in. Depending on the Controller and Action I am able to extract what i need for where i am at.

Any ideas as to why it is not working in the View. And also if there is a cleaner and easier way to do this - I'm all ears!

Thanks

UPDATE: I did a check in the view - just returning the ViewBag and it is coming back true, but in the Controller it is saying it is false. I am not sure why that is. If ViewBag is set in the Controller as false It should show in the view as false, should it not?

Edit: By Request here is my ForEach loop.

<tbody>
   @foreach (var item in Model)
   {
     <tr>
        <td>
            @Html.DisplayFor(modelItem => item.UserName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Role)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LockoutEndDateUtc)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CompanyName)
        </td>
        <td>

          @if (ViewBag.Edit == true)
          {
             @Ajax.ModalDialogActionLink("Edit", "Edit", "Edit User", "btn btn-warning btn-sm", new { UserName = item.UserName })
          }
          @if (User.IsInRole("Administrator"))
          {
             @Ajax.ModalDialogActionLink("PW Reset", "SendResetPassword", "Account", "Reset Password", "btn btn-info btn-sm", new { UserName = item.UserName })
             <text>&nbsp;</text>
             @Ajax.ModalDialogActionLink("Conf E-Mail", "SendEmailConfirm", "Account", "Email Confirmation", "btn btn-info btn-sm", new { UserName = item.UserName })
          }
          @if ((item.UserName.ToLower() != this.User.Identity.Name.ToLower()))
          {
            if (ViewBag.Delete == true)
            {
               @Html.ActionLink("Delete", "Delete", null, new { UserName = item.UserName },
               new { onclick = "return Confirm('Are you sure you want to delete this user?');", @class = "btn btn-danger btn-sm" })
             }
             <div class="btn-group">
                 @Html.ActionLinkAuthorized("Edit Roles", "Edit", "Roles", new { UserName = item.UserName }, new { @class = "btn btn-warning btn-sm" }, true)
             </div>
         }
        </td>
     </tr>
    }
 </tbody>

Update: For a complete answer to this go to this post.

stackoverflow.com/questions/60173428/

the following line returns collection of booleans :

menuaccess.Where(i => i.MenuURL == controllerName).Select(i => (i.IsUpdate));

so, ViewBag.Edit (same explanation for others which are assigned to ViewBag)

That is the reason why @if (ViewBag.Edit = true) is not evaluated correctly.

To fix this, modify the section of code to use FirstOrDefault() to return just one element from collection in controller as follows:

if (GetOrPost == "GET")
 {
    if (actionName == "add" || actionName == "index" || actionName == "create" || actionName == "edit" || actionName == "delete" || actionName == "multiviewindex")
    {
      ViewBag.Add = menuaccess.Where(i => i.MenuURL == controllerName).Select(i => (i.IsAdd)).FirstOrDefault();
      ViewBag.Read = menuaccess.Where(i => i.MenuURL == controllerName).Select(i => (i.IsRead)).FirstOrDefault();
      ViewBag.Create = menuaccess.Where(i => i.MenuURL == controllerName).Select(i => (i.IsCreate)).FirstOrDefault();
      ViewBag.Edit = menuaccess.Where(i => i.MenuURL == controllerName).Select(i => (i.IsUpdate)).FirstOrDefault();
      ViewBag.Delete = menuaccess.Where(i => i.MenuURL == controllerName).Select(i => (i.IsDelete)).FirstOrDefault();
    }
  }

Please note, I recommended using FirstOrDefault() on the assumption that collection will contain same value/s. What I meant by same value/s is collection contain either all true or all false but not mix of true and false.

If your collection contains both true and false then you need to use Any as follows:

if (GetOrPost == "GET")
{
    if (actionName == "add" || actionName == "index" || actionName == "create" || actionName == "edit" || actionName == "delete" || actionName == "multiviewindex")
    {
      ViewBag.Add = menuaccess.Any(i => i.MenuURL == controllerName && i.IsAdd);
      ViewBag.Read = menuaccess.Any(i => i.MenuURL == controllerName && i.IsRead);
      ViewBag.Create = menuaccess.Any(i => i.MenuURL == controllerName && i.IsCreate);
      // Any will be evaluated to true if any of item's MenuURL is equal to controllerName and IsUpdate set to true. false will be returned otherwise. Same explanation for others as well.
      ViewBag.Edit = menuaccess.Any(i => i.MenuURL == controllerName && i.IsUpdate);
      ViewBag.Delete = menuaccess.Any(i => i.MenuURL == controllerName && i.IsDelete);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM