建立MVC CMS

时间:2010-11-04 13:18:42

标签: asp.net-mvc content-management-system wysiwyg template-engine

我需要一个简单的功能来在这些页面上添加页面/更改内容。我已经看过n2和其他预构建的CMS工具,但这些是我需要的简单CMS功能的高级方法。

最好的方法是什么?我已经有了一个MVC应用程序,我想添加/构建一个简单的功能,如:

  1. 指定模板
  2. 向该模板添加区域
  3. 通过wysiwyg添加内容。
  4. 不确定从哪里开始。

    任何信息非常感谢。 感谢

    这适用于.NET MVC

1 个答案:

答案 0 :(得分:10)

假设你正在使用ASP.NET MVC而你想保持简单,那么这样的事情:

public abstract class TemplateBase
{
    public abstract string TemplateName { get; }
}

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");
    }
}

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");
    }
}

// TODO Add more template types

public class AreaContainer
{
    public string ContainerName { get; set; }
    public IList<AreaBase> Areas { get; protected set; }

    public AreaContainer(string name)
    {
        ContainerName = name;
        Areas = new List<AreaBase>();
    }
}

public abstract class AreaBase
{
    public abstract string AreaName { get; }
}

public class HtmlArea : AreaBase
{
    public override string AreaName { get { return "HTML content"; } }
    public string HtmlContent { get; set; }
}

// TODO Add more area types

public class Page
{
    public int Id { get; set; }
    public string Title { get; set; }
    public TemplateBase Template { get; set; }
}

用于编辑现有页面的控制器操作可能类似于:

public class PageAdminController : Controller
{
    [HttpGet]
    ActionResult Edit(int id) 
    {
        var page = GetPageFromStorageById(id);
        // TODO If the page is not found, issue 404
        return View(page);
    }

    // ...
}

在视图(Views/PageAdmin/Edit.aspx)中,应该强烈键入ViewPage<Page>,如果您创建了局部视图,则可以使用HtmlHelper.EditorFor(...)方法呈现相应的模板视图对于每种模板类型:

<!-- Inside the edit view for Page (Edit.aspx) -->
<%: Html.HiddenFor(m => m.Id) %>
<%: Html.EditorFor(m => m.Title) %>
<%: Html.EditorFor(m => m.Template) %>

在文件夹Views/PageAdmin/EditorTemplates中,您可以为每个模板和区域类型(即SingleColumnTemplate.ascxTwoColumnTemplate.ascxHtmlArea.ascx)放置部分修改视图。您可能还想为AreaContainer创建部分视图。

对于接收已编辑页面的控制器操作,事情变得更复杂一些。由于Page具有类型为TemplateBase的属性,这是一个抽象类,DefaultModelBinder将不知道如何填充它。您可以通过编写自定义模型绑定器来解决这个问题,该绑定器以某种方式“知道”要实例化的实现类。怎么会知道呢?我能想到的一个选项是在视图中包含一个隐藏字段,其中包含页面模板的实际运行时类型的名称。我想这是一个黑客攻击,但是因为你在简单之后,我认为它会好起来的。在这种情况下,只需在RuntimeTypeName类中包含一个名为TemplateBase的属性:

public string RuntimeTypeName { get { return GetType().FullName; } }

由于它只是调用GetType(),这是默认情况下被所有类型覆盖的虚方法,它将返回运行时模板类型的名称。

然后,您必须确保为TemplateBase实现创建的部分视图包含TemplateBase.RuntimeTypeName属性的(隐藏)字段。换句话说,在SingleColumnTemplate.ascxTwoColumnTemplate.ascx中你会有这一行:

<%: Html.HiddenFor(m => m.RuntimeTypeName) %>

利用此信息创建正确类型模板的模型绑定器可能如下所示:

/// <summary>
/// Model binder hack that builds upon the DefaultModelBinder, 
/// but that can detect the "proper" subclass/implementing class 
/// type for a model, assuming the name of that type is contained
/// in a field called "RuntimeTypeName".
/// </summary>
public class InheritanceSupportingModelBinder : DefaultModelBinder
{
    // Assume that the name of the field that contains the 
    // runtime type name is called "RuntimeTypeName"
    public const string RuntimeTypeNameField = "RuntimeTypeName";
    private Type RuntimeType { get; set; }

    // This method is called by the DefaultModelBinder to find out which
    // properties of the current model that it should attempt to bind
    protected override PropertyDescriptorCollection GetModelProperties(
        ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // If we have found out the runtime type of the model through
        // looking at the "special" field above, use the properties of that type.
        // Otherwise, use the default behavior.
        if (RuntimeType != null)
        {
            return TypeDescriptor.GetProperties(RuntimeType);
        }
        else
        {
            return base.GetModelProperties(controllerContext, bindingContext);
        }
    }

    // This method is called by the DefaultModelBinder when it 
    // tries to create an instance of the model class. If the 
    // class is abstract, an exception will be thrown. Therefore
    // we try to read the name of the actual type from the 
    // RuntimeTypeName (hidden) field and return an instance of that type.
    protected override object CreateModel(ControllerContext controllerContext, 
                                          ModelBindingContext bindingContext, 
                                          Type modelType)
    {
        if (bindingContext.ValueProvider.ContainsPrefix(
            bindingContext.ModelName + "." + RuntimeTypeNameField))
        {
            var result = bindingContext.ValueProvider.GetValue(
                bindingContext.ModelName + "." + RuntimeTypeNameField);

            if (result != null && !string.IsNullOrEmpty(result.AttemptedValue))
            {
                // Check that the type indicated by the hidden field is really
                // a subclass of (or implementing) the indicated base class
                var tempType = Type.GetType(result.AttemptedValue);
                if (modelType.IsAssignableFrom(tempType))
                {
                    RuntimeType = modelType = tempType;
                }
            }
        }
        return base.CreateModel(controllerContext, bindingContext, modelType);
    }
}

免责声明:我自己是ASP.NET MVC的初学者,所以这个模型绑定器可能有问题。我通过查看DefaultModelBinder的源代码并通过反复试验将它放在一起。这只是一个例子,但根据我的(快速和肮脏)测试,它似乎有效。

当然,您需要在Global.asax中注册它才能启动它:

ModelBinders.Binders.Add(
    typeof(TemplateBase), 
    new InheritanceSupportingModelBinder());

但我们还没有完成!请记住,AreaContainer.Areas集合的类型为IList<AreaBase> - 并且由于AreaBase也是一个抽象类,我们必须应用相同的hack才能正确绑定它。也就是说,将RuntimeTypeName属性添加到AreaBase类,并在AreaBase中为Global.asax类注册我们的自定义模型绑定器。

如果到目前为止我们已经执行了所有这些步骤,我们可以在PageAdminController上使用一种操作方法来处理看起来像这样的页面的编辑:

[HttpPost]
public ActionResult Edit(Page page)
{
    if (!ModelState.IsValid)
    {
        return View(page);
    }
    // TODO Save page to database or whatever
    // TODO Redirect to page index
}

创建新页面的操作方法留作练习,不应该那么困难(用户从列表中选择模板,显示正确的表单,如上所述的后处理操作)。

显示页面应该是微不足道的,只需使用HtmlHelper.DisplayFor(...)而不是EditorFor(...),创建相应的部分视图并进行设置。

对于WYSIWYG内容编辑,您可能希望使用第三方组件。 CKEditorTinyMCEYUI Rich Text EditorTelerik Editor就是一些例子。

这是我对此的看法!欢迎所有评论;正如我所提到的,我自己正在学习ASP.NET MVC,如果我的错误被那些了解得更好的人指出,那将会很棒。