我尝试创建一些 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 助手,它在 View 中具有以下格式:
@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);
}
}
要以 MvcForm
的方式使用此 MvcTag
,我们必须定义一个扩展
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>
}
关于asp.net-mvc - ASP.NET MVC Html 帮助程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23173128/