This is for .net MVC project i’m working on
I have the following classes:
public abstract class TemplateBase
{
public abstract string TemplateName { get; }
public string RuntimeTypeName { get { return GetType().FullName; } }
}
and 2 classes that inherit from it:
public class TwoColumnTemplate : TemplateBase
{
public override string TemplateName { get { return "Two-column page"; } }
public AreaContainer LeftColumn { get; protected set; }
public AreaContainer RightColumn { get; protected set; }
public TwoColumnTemplate()
{
LeftColumn = new AreaContainer("Left column");
RightColumn = new AreaContainer("Right column");
}
}
public class SingleColumnTemplate : TemplateBase
{
public override string TemplateName { get { return "Single-column page"; } }
public AreaContainer CenterColumn { get; protected set; }
public SingleColumnTemplate()
{
CenterColumn = new AreaContainer("Center column");
}
}
and a contentpage class that is used for displaying/modifying html content
public class ContentPage
{
public virtual int ContentPageId { get; set; }
public virtual string Title { get; set; }
public TemplateBase Template { get; set; }
}
Now the question. I’ve created a model binder that binds ContentPage and I do get the data to my ActionResult like so:
[HttpPost]
public ActionResult Edit(ContentPage row)
{
return this.View(row);
}
row does have the right data however I can’t access Left or Right column data because abstract class TemplateBase. To clerify is there a way to dynamically cast “row” object to a correct class (SingleColumn or TwoColumn) type?
Instead of this using if/else is there a better way?. Maybe using reflections?
thanks
[HttpPost]
public ActionResult Edit(ContentPage row)
{
var sb = new StringBuilder();
if (row.Template.RuntimeTypeName == "TwoColumn")
{
TwoColumnTemplate template = (TwoColumnTemplate)row.Template;
}
else
{
SingleColumnTemplate template = (SingleColumnTemplate)row.Template;
}
return this.View(row);
}
You do not need the
RuntimeTypeNameproperty at all. The correct way to do type testing would be something like this:However, this screams out for proper OO design. If you have a hierarchy of classes, and you are constantly testing if some object is of some class, your class model is severely broken.
Perhaps your template classes themselves should be emitting their own HTML or view state objects via an abstract method? The type system gives you all the power you need to solve this problem without testing if an object is of a particular type.