Handling empty collections in view model with spark
-
05-07-2019 - |
Question
In spark when sending a view model to the view when a collection is empty is causing me some headaches like so:
<input value="model.addresses[0].street" />
Where "model.addresses" may be empty and thus gives an NRE.
Is there anyway to handle this other than populating the collections prior to rendering. This is a bit of a pain as it reqiures some custom processing to make sure they are populated. I was thinking the spark conditional attribute would work:
<input value="model.addresses[0] != null?model.addresses.street" />
But I feel like there may be a better way to handle these situations.
Solution
From spark documentation:
The syntax $!{expression} can also be used if you want to ensure any null values and NullReferenceException that result from the expression will produce no output at all.
http://sparkviewengine.com/documentation/expressions#Nullsinexpressions
OTHER TIPS
I see couple of other options:
- Use partial view for list items and check for NULLs once in there.
- Add extension method to simplify the NULL checks.
These are one of the most used extension methods I have written for myself:
public static TResult PropGet<TObject, TResult>(this TObject obj, Func<TObject, TResult> getter, TResult defaultValue) {
if (ReferenceEquals(obj, null))
return defaultValue;
var res = getter.Invoke(obj);
return ReferenceEquals(res, null) ? defaultValue : res;
}
public static TResult PropGet<TObject, TResult>(this TObject obj, Func<TObject, TResult> getter) {
return PropGet(obj, getter, default(TResult));
}
So on your view you could write this:
<input value="model.addresses[0].PropGet(a => a.street)" />