2011-03-22 35 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

相关问题