views:

161

answers:

2

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.

+1  A: 

I see couple of other options:

  1. Use partial view for list items and check for NULLs once in there.
  2. 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)" />
Dmytrii Nagirniak
+1  A: 

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

LukLed
this is exactly what i was looking for. I can't believe i missed that in the documentation. thank you!
Sean Chambers