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.
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With