In the view, I ask, or do not set a specific property ViewBag - ViewBag.SomeData . In the _Layout.cshtml file _Layout.cshtml I need to output or not output a specific block depending on whether SomeData is SomeData in the ViewBag , and how to do it?

While I use for this ViewData and its function ContainsKey , but this is how it ViewBag in some places in ViewBag and in others, where you need to know if a property is defined and where not - ViewData , it’s not very nice to use this and that. Or everywhere it is necessary to switch to ViewData .

    2 answers 2

    Just check this property for null

     @if (ViewBag.SomeData != null) { // Действия, если SomeData определена } else { // Действия, если SomeData не определена } 

      All data from the ViewBag automatically fall into the ViewData dictionary, so you can always safely check them through ViewData.ContainsKey .

      Actually, the ViewBag is a dynamic wrapper on top of the ViewData , this can be seen with the help of the code:

       PropertyInfo viewDataProperty = ViewBag.GetType() .GetProperty("ViewData", BindingFlags.Instance | BindingFlags.NonPublic); var value = viewDataProperty.GetValue(ViewBag); Object.ReferenceEquals(value, ViewData); // вернет true 

      With ViewBag you can use something like ViewBag.SomeData != null maximum, but this does not guarantee the absence of a property - it may be present, but be equal to null.