如何使用动态内容创建可重用的HTML片段

时间:2011-03-22 10:25:56

标签: asp.net-mvc asp.net-mvc-3

我正在尝试创建一个可重用的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>

我该如何对此进行流式处理。优雅会很好: - )

1 个答案:

答案 0 :(得分: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>
}