0

I have a shared view that is used by 4 different parent views. In the shared view, I need to do a simple check:

if (Model.foo == barr)
   {...]

The problem is, in one of the 4 models, there is no foo. I'd rather not add it to the one model to just avoid the error:

does not contain a definition for 'foo'

I'm wondering if I can do a pre-check, something like..

if (Model.Contains(foo) && Model.foo == bar)
{...}

Is anything like that possible?

Casey Crookston
  • 13,016
  • 24
  • 107
  • 193

2 Answers2

1

You could use reflection, if you want to check if an object contains a property:

if ((typeof(Model)).GetProperty("foo") && Model.foo == bar)

but it seems a bit awkward the whole thing. Basically, I have never seen reflection to be used in a View.

Christos
  • 53,228
  • 8
  • 76
  • 108
0

I found a work-around that seems to be pretty good. In each of the four models, i added a property:

public int MySharedViewSource { get; set; }

And then in the view...

if (Model.MySharedViewSource == 1}
  { 
      // Wnatever is in here only gets executed if the source is 1,
      // so I can reference Model.foo and not worry about errors 
      // when using this shared view from a model that does not have foo in it.
  }
Casey Crookston
  • 13,016
  • 24
  • 107
  • 193