What is the PHP isset equivalent in C # .NET 4 for properties of "dynamic" objects?

I am working with MVC 3 the moment I use ViewBag. I would like to check if one of the ViewBag properties has been assigned. I know in PHP you can do isset (variable), but is there something similar in .NET 4?

The scenario is that I am making a nested layout that accepts a section title and section subtitle through a ViewBag. They are separated by a separator, and a subheading is optional. I do not want to display the delimiter if the subtitle is not set.

This is how I imagine where isset will be replaced with .NET 4 equivelant.

@section header { <h2>@ViewBag.SectionTitle</h2> @if(isset(ViewBag.SectionSubTitle)) { <div id="section-title-seperator"> - </div><h3>@ViewBag.SectionSubTitle</h3> } } 

Next to the direct answer to my question, I am also open to alternative solutions (in case I abuse ViewBag).

Thanks in advance.

+6
dynamic asp.net-mvc-3 razor
source share
1 answer

You can check if this is null as follows:

@if(ViewBag.SectionSubTitle != null) .

isset() in PHP actually just checks to see if a value is present. From the manual:

isset () will return FALSE if testing a variable that was set to NULL

You can also use ViewDataDictionary.ContainsKey in the ViewData property. Because ViewData["SectionSubTitle"] equivalent to ViewBag.SectionSubTitle , so in this case you can do:

@if(ViewData.ContainsKey("SectionSubTitle"))

+14
source share

All Articles