某些網站,例如電商類的,常常會有線上更改網頁廣告版型或內容的需求。但是在設計上,要求彈性是很困難的,在過往的工作經驗中,是事先提供幾種固定版型,然後供行銷人員選擇,如果要加新版或更改版型,網站就得上版。

但有一種簡單的做法可以實現,程式碼如下:

首先定義一個提供內容的類別:

public class ContentManager
{
    private Dictionary<string, string> _content;

    private ContentManager()
    {
        _content = new Dictionary<string, string>();
        _content["Test1"] = @"<span>Test1</span>";
        _content["Test2"] = @"<h1>Test Title</h1>";
        _content["Test3"] = @"<span>My name is {0}</span>";
    }

    public static ContentManager Instance = new ContentManager();

    public string GetContent(string contentKey)
    {
        string content = string.Empty;
        if(_content.ContainsKey(contentKey))
        {
            content = _content[contentKey];
        }

        return content;
    }
}

為了方便示範,內容是寫死在 Dictionary 物件中,可視需求存在資料庫或 Redis Server 中。

接下來是 Controller:

public IActionResult Index()
{
    ViewData["Content"] = ContentManager.Instance.GetContent("Test2");
    ViewData["Content2"] = string.Format(ContentManager.Instance.GetContent("Test3"), "Peter");

    return View();
}

最後在 View 中使用:

<div>
    <h1>Test Area</h1>
    @Html.Raw(ViewData["Content"])
    @Html.Raw(ViewData["Content2"])
</div>

簡單方便。