ASP.NET MVC Html Helper

pit*_*dis 3 asp.net-mvc extension-methods html-helper

我尝试创建一些Html Helpers,它将有一个开始标记和结束标记,其中包含其他内容,如Html.BeginForm.例如在Razor中我们可以使用Html.BeginForm帮助器,它具有以下语法:

    @using (Html.BeginForm())
    {
    }
Run Code Online (Sandbox Code Playgroud)

此代码将包含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>");
    }
Run Code Online (Sandbox Code Playgroud)

然后我使用以下示例使用帮助程序:

    @Html.StartForm()
    contents
    @Html.EndForm()
Run Code Online (Sandbox Code Playgroud)

但我希望能够制作一个html助手,它在视图中具有以下格式:

    @using (Html.MyForm())
    {
            <text>contents</text>
    }
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决这个问题,因为我甚至不知道如何搜索它.

vbn*_*vbn 6

您可以像实现方式一样定义类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);
    }
}
Run Code Online (Sandbox Code Playgroud)

为了在使用它MvcTag的方式MvcForm中使用它,我们必须定义一个扩展

public static class HtmlHelperExtensions
{
    public static MvcTag BeginTag(this HtmlHelper htmlHelper, string tag)
    {
        return new MvcTag(htmlHelper.ViewContext, tag);
    }
}
Run Code Online (Sandbox Code Playgroud)

就是这样.现在您可以将其用作:

@using(Html.BeginTag("div")) @* This creates a <div>, alternatively, you can create any tag with it ("span", "p" etc.) *@
{ 
    <p>Contents</p>
}
Run Code Online (Sandbox Code Playgroud)