【发布时间】:2020-02-12 23:17:26
【问题描述】:
我遇到了 ViewBag 无法在视图中工作的问题。控制器返回我认为我需要的东西..
在调试时我有 Current = false,然后在结果视图中我也有 false。该位设置为假。 似乎所有 ViewBag 项目都为 Current 返回 False。
当我在我的视图中调用 ViewBag 时,它似乎没有做任何事情。它也没有错。
这是我从数组中获取当前布尔信息的代码部分。
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));
}
}
这是视图中的用法:
@if (ViewBag.Edit = true)
{
@Ajax.ModalDialogActionLink("Edit", "Edit", "Edit User", "btn btn-warning btn-sm", new { UserName = item.UserName })
}
MenuOfRole 为已登录的 RoleUser 带回所有权限。根据控制器和操作,我能够提取我所在位置所需的内容。
关于为什么它在视图中不起作用的任何想法。而且,如果有更清洁、更简单的方法来做到这一点 - 我全神贯注!
谢谢
更新: 我在视图中进行了检查 - 只是返回 ViewBag 并且它返回为真,但在控制器中它说它是假的。我不确定为什么会这样。如果 ViewBag 在 Controller 中设置为 false 应该在视图中显示为 false,不是吗?
编辑:按请求这里是我的 ForEach 循环。
<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> </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>
更新:有关此问题的完整答案,请参阅此帖子。
【问题讨论】:
-
If ViewBag is set in the Controller as false It should show in the view as false, should it not?--- 也许您在分配之前或在不同的控制器操作/视图中检查 ViewBag,因为您仅在操作名称在特定列表中时才设置 ViewBag 值? -
是的,控制器中的 ViewBag 在 BaseController 中,这将是 UsersController 但 UsersController : BaseController。现在它似乎正在工作。在我可以说它是 100% 之前,我还有测试要做。感谢您的帮助!
标签: c# asp.net-mvc razor-pages