2011-03-22 34 views
2

我試圖創建一個可重用的HTML片段,我希望能夠接受其他HTML作爲某種參數。如何使用動態內容創建可重用的HTML片段

我可重用的代碼是

<div class="dialog" id="@Model.HtmlId"> 

    <!-- My reusable code needs to go here --> 
</div> 

創建一個局部視圖很容易,但問題是,部分景色接受模型作爲參數。

我現在的解決方案很難看。

@Html.Partial("_startDialog", new { HtmlId="someIdGoesHere" }); 

<form> 
    <!-- Some form elements go here --> 
</form> 

@Html.Partial("_endDialog"); 

這使得

<div class="dialog" id="@Model.HtmlId"> 

    <form> 
    <!-- Some form elements go here --> 
    </form> 
</div> 

如何流線這一點。雅將是不錯:-)

回答

3

這應該做的伎倆:

public class MvcDialog : IDisposable 
{ 
    public MvcDialog(ViewContext context, IDictionary<string, object> htmlAttributes) 
    { 
     this.context = context; 
     this.htmlAttributes = htmlAttributes; 

     Begin(); 
    } 

    private ViewContext context; 
    private IDictionary<string, object> htmlAttributes; 
    private TagBuilder tag; 
    private bool disposed; 

    protected virtual void Begin() 
    { 
     tag = new TagBuilder("div"); 
     tag.MergeAttributes(htmlAttributes); 
     tag.AddCssClass("dialog"); 

     context.Writer.Write(tag.ToString(TagRenderMode.StartTag)); 
    } 

    public virtual void End() 
    { 
     Dispose(true); 
    } 

    protected virtual void Dispose(bool disposing) 
    { 
     if (!disposed) 
     { 
      disposed = true; 
      context.Writer.Write(tag.ToString(TagRenderMode.EndTag)); 
     } 
    } 

    public void Dispose() 
    { 
     Dispose(true); 
     GC.SuppressFinalize(this); 
    } 
} 

public static class MvcDialogExtensions 
{ 
    public static MvcDialog Dialog(this HtmlHelper self) 
    { 
     return Dialog(self, new RouteValueDictionary()); 
    } 
    public static MvcDialog Dialog(this HtmlHelper self, object htmlAttributes) 
    { 
     return Dialog(self, new RouteValueDictionary(htmlAttributes)); 
    } 
    public static MvcDialog Dialog(this HtmlHelper self, IDictionary<string, object> htmlAttributes) 
    { 
     return new MvcDialog(self.ViewContext, htmlAttributes); 
    } 
} 

用法:

@using (Html.Dialog(new { id = "mightyDialog" })) 
{ 
    <text>awesome content</text> 
} 
+0

盧卡斯嗨,該解決方案爲純文本的偉大工程,但如果您嘗試

<輸入類型='文字'>
而不是,然後它停止工作:-(很好的回答,雖然。 – 2011-03-23 05:18:55

+1

你不需要''當你的內容s與html標籤的蛋撻。然而,它應該(而且它對我來說)無論如何都能正常工作,你能發佈你準確的行爲嗎? – 2011-03-23 07:39:14

相關問題