如何创建具有动态内容的可重用HTML [英] How to create a reusable piece of HTML with dynamic contents
本文介绍了如何创建具有动态内容的可重用HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个可重用的HTML片段,希望能够接受其他HTML作为某种参数.
I'm trying to create a reusable fragment of HTML that I'd like to be able to accept additional HTML as some sort of parameter.
我的可重用代码是
<div class="dialog" id="@Model.HtmlId">
<!-- My reusable code needs to go here -->
</div>
创建局部视图很容易,但是问题在于局部视图接受模型作为参数.
Creating a partial view is easy, but the problem is that partial views accept a Model as a parameter.
我目前的解决方案很丑.
My current solution is ugly.
@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>
我如何精简这一行.优雅会很好:-)
How can I stream line this. Elegance would be nice :-)
推荐答案
这应该可以解决问题:
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>
}
这篇关于如何创建具有动态内容的可重用HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文