ITWorker ITWorker - 3 months ago 12
C# Question

In Razor, how to check existence of an object in ViewBag IEnumerable object based on a property of the element?

I have model object called

AppPrivilege
, and it contains a public string property called
PrivilegeName
. In a controller, I generate a collection of those objects, and put them in the ViewBag, as follows (the other object types are all custom to my project):

SQLRolerecord toCheckPrivs = new SQLRolerecord();
IEnumerable<AppPrivilege> privsOfUser = toCheckPrivs.getPrivsForRole(roleUser);
ViewBag.PrivilegeSet = privsOfUser;
return View();


Now in a view, how can I check whether there exists any element
AppPrivilege
that has a
PrivilegeName
of my choosing, such as "Read" for example? Here is the structure I am trying to achieve in the view:

@if (ViewBag.PrivilegeSet != null)
{
if(ViewBag.PrivilegeSet.Contains(/*search criteria for PrivilegeName*/))
{
//valid code here

}
}


My approach to address this requirement consisted of generating a potentially large string of all the
PrivilegeName
values concatenated, and passing that through the ViewBag, upon which I could do string checking in the view. However, this seems not performance friendly, so I want to do it in a more proper way.

Thank you.

Answer

ViewBag is a dynamic dictionary. You need to cast it to the specific type, IEnumerable<AppPrivilege> so that you can run LINQ extension methods on that.

Here is the code which use the Any() method to see at leaset one item exist in the ViewBag.PrivilegeSet collection with the PrivilegeName "Read"

@if (ViewBag.PrivilegeSet != null)
{
   var items = ViewBag.PrivilegeSet as IEnumerable<AppPrivilege>;
   if(items.Any(d=>d.PrivilegeName=="Read"))
   {
     <h1>Exist!</h1>
   }
}
Comments