我有以下抽象类:
public abstract class TemplateBase
{
public abstract string TemplateName { get; }
public string RuntimeTypeName { get { return GetType().FullName; } }
public abstract List<AreaContainer> TemplateAreas { get; }
}
然后这2个继承类:
public class SingleColumnTemplate : TemplateBase
{
public override string TemplateName { get { return "Single column"; } }
public AreaContainer CenterColumn { get; private set; }
public SingleColumnTemplate()
{
this.CenterColumn = new AreaContainer("Middle");
}
private List<AreaContainer> templateAreas;
public override List<AreaContainer> TemplateAreas
{
get
{
if (this.templateAreas == null)
{
this.templateAreas = new List<AreaContainer>() { this.CenterColumn };
}
return this.templateAreas;
}
}
}
和
public class TwoColumnTemplate : TemplateBase
{
public override string TemplateName { get { return "Two column"; } }
public AreaContainer LeftColumn { get; private set; }
public AreaContainer RightColumn { get; private set; }
public TwoColumnTemplate()
{
LeftColumn = new AreaContainer("Left");
RightColumn = new AreaContainer("Right");
}
private List<AreaContainer> templateAreas;
public override List<AreaContainer> TemplateAreas
{
get
{
if (this.templateAreas == null)
{
this.templateAreas = new List<AreaContainer>() { this.LeftColumn, this.RightColumn };
}
return this.templateAreas;
}
}
}
我还有这个类,它是我的编辑模型:
public class ContentPage
{
public virtual int ContentPageId { get; set; }
public virtual string Title { get; set; }
public TemplateBase Template { get; set; }
}
问题:
对于我的 ActionResults,我有以下内容:
[HttpGet]
public ActionResult Edit()
{
var row = new ContentPage();
var template = new TwoColumnTemplate();
// Areas
HtmlArea html_left = new HtmlArea();
html_left.HtmlContent = "left area html content";
HtmlArea html_right = new HtmlArea();
html_right.HtmlContent = "right area html content";
template.LeftColumn.Areas.Add(html_left);
template.RightColumn.Areas.Add(html_right);
row.Template = template;
return View(row);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult Edit(ContentPage row)
{
// Here i could loop through List -TemplateAreas and save each template Area to Db. I guess that would work
return this.View(row);
}
问题:
对于 HttpGet - 我将如何从数据库加载行模板?因为它可以是 SingleColumnClass 或 TwoColumnClass。
我的 ViewModel 会如何解决这个问题?
谢谢
最佳答案
您可以编写自己的模型绑定(bind)器来负责绑定(bind)TemplateBase。您仍然需要有一种方法(在模型绑定(bind)器中)知道您将使用运行时的类型,但您始终可以将其委托(delegate)给某种工厂或服务定位器。我进行了快速的谷歌搜索,这是我发现的一篇博客文章,它为您提供了一些为类似场景制作模型绑定(bind)程序的信息:
http://weblogs.asp.net/bhaskarghosh/archive/2009/07/08/7143564.aspx
编辑:该博客遗漏了如何向 MVC 告知模型绑定(bind)程序。当应用程序启动时,您可以将模型绑定(bind)器添加到 System.Web.Mvc.ModelBinders.Binders
HTH
关于c# - .net从抽象类创建对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4592925/