經過多年的WebForms工作,我最近開始向MVC過渡。我正在嘗試創建一個可插入的輕量級內容編輯模塊,但我遇到了一些問題。MVC 5自定義HtmlHelper輕量級內容編輯
的想法很簡單:創建一個名爲EditableSimpleHtml的HtmlHelper可在@using使用... {}語法,以便下面可以在Razor視圖來實現:
@using (Html.EditableSimpleHtml("MyKey"))
{
<h3>Test</h3>
<p>
1<br />
</p>
}
之間的值{...}是在數據存儲中找不到內容時的默認值。
我創建了一個HtmlHelper。下面是一個簡化版本:
public static IDisposable EditableSimpleHtml(this HtmlHelper helper, string key)
{
// Get the content from the data storage using the key (I will not show the provider itself, its just a provider that will access a db)
var provider = ContentEditing.Provider;
string value = provider.GetValue(key);
if (value == null)
{
// No value found in the data storage for the supplied key, we have to use the default value from within the @using... { } statement
// Can I get that value here? I want to to store it initialy in the data storage
value = "..."; // How to get html from within the @using... { }?
}
return new ContentEditableHtmlString(helper, value);
}
public class ContentEditableHtmlString : IDisposable
{
private readonly HtmlHelper _helper;
public ContentEditableHtmlString(HtmlHelper helper, string value)
{
_helper = helper;
var builder = new TagBuilder("div");
var writer = _helper.ViewContext.Writer;
writer.Write(builder.ToString(TagRenderMode.StartTag));
writer.Write(value);
}
public void Dispose()
{
_helper.ViewContext.Writer.Write("</div>");
}
}
的問題是,我不能從@using內得到(默認)的內容... {}語句中的HtmlHelper,或者至少我不知道怎麼樣。我需要它,以防我想將它存儲到數據庫中。
第二個問題是,@using ... {}語句之間的值將始終呈現。在可以從數據存儲裝載內容的情況下,我希望將默認值替換爲數據存儲中的值。
有沒有辦法做到這一點,或者我開始完全錯誤的路徑?
發現一篇博客文章,概述瞭如何讓助手像Html.BeginForm():HTTP: //scatteredcode.wordpress.com/2012/01/22/mimicking-html-beginform-to-reduce-html-div-duplication-in-asp-net-mvc-sites/ –
@MichaelDunlap感謝您的建議,但問題不在於我不知道如何創建一個可以像Html.BeginForm()一樣使用的幫助器)。那實際上很容易。但更多的是我想要使用/實現它的方式,正如我在兩個主要問題中所描述的那樣。 –