views:

44

answers:

2

Let's say I have some content classes like Page, TabGroup, Tab, etc. Certain of those will be implementing my IWidgetContainer interface - it means they will geet an additional field named ContainedItems from the interface and some methods for manipulating this field.

Now I need to reflect the fact that some class implements this interface by rendering out some special custom controls in my ASP.NET MVC Views (like jQuery Add/Remove/Move/Reorder buttons).

For instance, TabGroup will implement IWidgetContainer because it will contain tabs but a tab will not implement it because it won't have the ability to contain anything.

So I have to somehow check in my view, when I render my content objects (The problem is, I use my base class as strong type in my view not concrete classes), whether it implements IWidgetContainer.

How is that possible or have I completely missed something?

To rephrase the question, how do you reflect some special properties of a class (like interface implementation) in the UI in general (not necessarily ASP.NET MVC)?

Here's my code so far:

[DataContract]
public class ContentClass
{
    [DataMember]
    public string Slug;

    [DataMember]
    public string Title;

    [DataMember]
    protected ContentType Type;
}

[DataContract]
public class Group : ContentClass, IWidgetContainer
{
    public Group()
    {
        Type = ContentType.TabGroup;
    }

    public ContentList ContainedItems
    {
        get; set;
    }

    public void AddContent(ContentListItem toAdd)
    {
        throw new NotImplementedException();
    }

    public void RemoveContent(ContentListItem toRemove)
    {
        throw new NotImplementedException();
    }
}

[DataContract]
public class GroupElement : ContentClass
{
    public GroupElement()
    {
        Type = ContentType.Tab;
    }
}

Interface:

interface IWidgetContainer
{
    [DataMember]
    ContentList ContainedItems { get; set; }

    void AddContent(ContentListItem toAdd);
    void RemoveContent(ContentListItem toRemove);

}
+1  A: 

I may have misunderstood your question, but is there a problem with using the is keyword?

<% if (obj is IWidgetContainer) { %>
    <!-- Do something to render container-specific elements -->
<% } %>
Programming Hero
No, no problem with "is". I forgot one can use "is" with interfaces also. ;)
mare
+2  A: 

I think you are looking for

 void Foo(ContentClass cc)
 {
    if (cc is IWidgetContainer) 
    {
        IWidgetContainer iw = (IWidgetContainer)cc;
        // use iw
    }

 }
Henk Holterman