Verify Member Existence in Mvc ViewBag

Sometimes I have to check for the existence of a member inside the ViewBag from within Mvc View to make sure that for some problem the action forgot to assign a member. Inside my kind of razor I have:

@if(ViewBag.Utente.Ruolo.SysAdmin) 

How can I verify that ViewBag.Utente defined?

+4
source share
4 answers

You must check that all objects are zero or not. Utente , Utente.Ruolo and Utente.Ruolo.SysAdmin may be empty:

 @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 } } } 
+5
source

The easiest way is:

 @if (ViewBag.Utente != null) { // some code } 
+3
source

If you are using MVC4, you can use

 @if (ViewBag.Utente != null) 

For previous versions, take a look at these answers:

Checking for the presence of a ViewBag property for conditional JavaScript input

+2
source

You can use it,

 @if (string.IsNullOrEmpty(ViewBag.Utente.Ruolo.SysAdmin)) { } 

But if you want to verify that your users are verified or not, I think this is not very good.

+1
source

Source: https://habr.com/ru/post/1494518/


All Articles