Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is PHP's isset equivalent in c# .NET 4 for properties of 'dynamic' objects?

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

The scenario is that I am making a nested layout which takes a section title and a section subtitle through the ViewBag. They are seperated by a seperator and the sub title is optional. I don't want to display the seperator if the sub title is not set.

This is how I imagine it where isset would be replaced by the .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'm also open to alternate solutions (in case I'm abusing the ViewBag).

Thanks in advance.

like image 495
Matthijs Wessels Avatar asked Feb 09 '11 15:02

Matthijs Wessels


1 Answers

You can check if it is null like this:

@if(ViewBag.SectionSubTitle != null).

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

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

You can also use ViewDataDictionary.ContainsKey on your ViewData property. Because ViewData["SectionSubTitle"] is equavilient to ViewBag.SectionSubTitle so in this case you could do:

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

like image 68
Filip Ekberg Avatar answered Dec 07 '22 12:12

Filip Ekberg