Reputation: 2560
Sometimes I have to check the existence of a member inside the ViewBag from inside an Mvc View, to see if for any problem the action forgot to assign the member. Inside my Razor View I have:
@if(ViewBag.Utente.Ruolo.SysAdmin)
how can I check that ViewBag.Utente
is defined?
Upvotes: 3
Views: 4919
Reputation: 3787
You must check all objects are null or not. Utente
, Utente.Ruolo
and Utente.Ruolo.SysAdmin
may be null:
@if (ViewBag.Utente != null)
{
if (ViewBag.Utente.Ruolo != null)
{
if (!string.IsNullOrEmpty(ViewBag.Utente.Ruolo.SysAdmin))
{
//ViewBag.Utente.Ruolo.SysAdmin has value..you can use it
}
}
}
Upvotes: 4
Reputation: 1938
If you are using MVC4 you can use
@if (ViewBag.Utente != null)
For previous versions take a look at those answers:
Checking to see if ViewBag has a property or not, to conditionally inject JavaScript
Upvotes: 2
Reputation: 9145
As simple as this:
@if (ViewBag.Utente != null)
{
// some code
}
Upvotes: 3
Reputation: 1263
You can you use it;
@if (string.IsNullOrEmpty(ViewBag.Utente.Ruolo.SysAdmin))
{
}
But if you want to check your users are confirmed or not, I think it is not a good way..
Upvotes: 1