I have some Razor code that has conditional logic based on whether a certain array variable is set. I’m having a heck of a time figuring out the best way to handle when it’s null and I’m not happy with my kludgy solution.
Here’s a simple example of what’s happening:
@{
if (ViewBag.Foo != null)
{
double[] bar = new double[ViewBag.Foo.Length];
}
}
Later on in the code, I’ll have something like this:
@if (ViewBag.Foo != null)
{
...some code that uses `bar` goes here ...
}
With that code, I get errors when ViewBag.Foo actually is null. I get an exception thrown complaining about the second section of code that uses bar and it not being in scope . However, in the execution, that second section will always be skipped.
After messing with it for awhile, I just did this instead:
double[] bar;
@{
if (ViewBag.Foo != null)
{
bar = new double[ViewBag.Foo.Length];
}
}
else
{
bar = new double[1];
}
With this change, the code works when ViewBag.Foo is null and non-null. There’s gotta be a better way to handle this… anyone?
This sort of work does not belong in a view:
The sort of problem you had is exactly why this is the case. Your problem came down to the fact that
barwas not correctly scoped. If instead this work was happing within a ViewModel, a similar mistake would have immediately given you a compiler error. Instead you don’t find out until you compile and use the application, and the error you are given can often be cryptic and difficult to track down.