我尝试创建一些 Html Helpers,它们将具有开始标记和结束标记,其中将包含其他内容,如 Html.BeginForm 那样。
例如,在 Razor 中,我们可以使用 Html.BeginForm 帮助器,其语法如下:
@using (Html.BeginForm())
{
}
此代码将包含 a 和 内大括号的内容。我解决打开和关闭包含内容的标签的唯一方法是使用两个 html 助手。我定义了两个 html 助手:
public static MvcHtmlString StartForm(this System.Web.Mvc.HtmlHelper helper)
{
return new MvcHtmlString("<form>");
}
public static MvcHtmlString EndForm(this System.Web.Mvc.HtmlHelper helper)
{
return new MvcHtmlString("</form>");
}
然后我使用以下示例来使用助手:
@Html.StartForm()
contents
@Html.EndForm()
但我希望能够制作一个 html 助手,它在视图中具有以下格式:
@using (Html.MyForm())
{
<text>contents</text>
}
有人可以帮助我解决这个问题,因为我什至不知道如何搜索它。
您可以像定义一个类一样MvcForm
已实施。下面的类允许您创建包含其他元素的标签。
public class MvcTag : IDisposable
{
private string _tag;
private bool _disposed;
private readonly FormContext _originalFormContext;
private readonly ViewContext _viewContext;
private readonly TextWriter _writer;
public MvcTag(ViewContext viewContext, string tag)
{
if (viewContext == null)
{
throw new ArgumentNullException("viewContext");
}
_viewContext = viewContext;
_writer = viewContext.Writer;
_originalFormContext = viewContext.FormContext;
viewContext.FormContext = new FormContext();
_tag = tag;
Begin(); // opening the tag
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Begin()
{
_writer.Write("<" + _tag + ">");
}
private void End()
{
_writer.Write("</" + _tag + ">");
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
End(); // Closing the tag
if (_viewContext != null)
{
_viewContext.OutputClientValidation();
_viewContext.FormContext = _originalFormContext;
}
}
}
public void EndForm()
{
Dispose(true);
}
}
为了利用这个MvcTag
以这样的方式MvcForm
使用时,我们必须定义一个扩展
public static class HtmlHelperExtensions
{
public static MvcTag BeginTag(this HtmlHelper htmlHelper, string tag)
{
return new MvcTag(htmlHelper.ViewContext, tag);
}
}
就是这样。现在您可以将其用作:
@using(Html.BeginTag("div")) @* This creates a <div>, alternatively, you can create any tag with it ("span", "p" etc.) *@
{
<p>Contents</p>
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)