2014-02-11 28 views
5

經過多年的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 ... {}語句之間的值將始終呈現。在可以從數據存儲裝載內容的情況下,我希望將默認值替換爲數據存儲中的值。

有沒有辦法做到這一點,或者我開始完全錯誤的路徑?

+0

發現一篇博客文章,概述瞭如何讓助手像Html.BeginForm():HTTP: //scatteredcode.wordpress.com/2012/01/22/mimicking-html-beginform-to-reduce-html-div-duplication-in-asp-net-mvc-sites/ –

+0

@MichaelDunlap感謝您的建議,但問題不在於我不知道如何創建一個可以像Html.BeginForm()一樣使用的幫助器)。那實際上很容易。但更多的是我想要使用/實現它的方式,正如我在兩個主要問題中所描述的那樣。 –

回答

2

您無法像現在這樣獲取@using{...}聲明中的html。

你可以做的最接近的事是使用Templated Razor Delegates

public static HelperResult EditableSimpleHtml(this HtmlHelper helper, string key, 
               Func<string, HelperResult> template) 
{ 
    var templateResult = template(null); 
    //you have your value here that you can return directly 
    //or you can return HelperResult to write to the response directly 
    var templateResultHtml = templateResult.ToHtmlString(); 

    return new HelperResult(writer => 
    { 
     templateResult.WriteTo(writer); 
    }); 
} 

而在你的看法:

@Html.EditableSimpleHtml("MyKey", @<text> 
            <h3>Test</h3> 
            <p>@DateTime.Now</p> 
            </text>) 
+0

有點知道我走錯了路。感謝您的建議替代方案。我將不得不回到繪圖板;) –