首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >ASPMVC4创建类似于Html.BeginForm的自定义html帮助方法

ASPMVC4创建类似于Html.BeginForm的自定义html帮助方法
EN

Stack Overflow用户
提问于 2013-01-09 21:14:40
回答 3查看 25.5K关注 0票数 17

我有以下html:

代码语言:javascript
复制
<div data-bind="stopBindings">

    <div data-viewId="languageList" data-bind="with: viewModel">
       <table>
              <tr>
                   <td ><label for="availableLanguages">Available Languages:</label></td>
              </tr>
       <table>
    </div>

</div>

我想做一个自定义的html助手,并像这样使用它(类似于Html.BeginForm)

代码语言:javascript
复制
@Html.BeginView()
{
    <table>
        <tr>
            <td ><label for="availableLanguages">Available Languages:</label></td>
        </tr>
    </table>
}

我开始制作我的helper方法

代码语言:javascript
复制
public static class BeginViewHelper
    {
        public static MvcHtmlString BeginView(this HtmlHelper helper, string viewId)
        {

            var parentDiv = new TagBuilder("div");
            parentDiv.MergeAttribute("data-bind", "preventBinding: true");
            return new MvcHtmlString();
        }

    }

我阅读了如何制作基本的html helper,但我看到的示例并没有给我提供在我的例子中如何制作它的信息。我是一个非常新的asp mvc和每一个帮助将非常感谢。

更新2:

显然,我遗漏了一些东西。在我看来,我将其称为:

代码语言:javascript
复制
@Html.BeginView()
{
    <table>
        <tr>
            <td ><label >test</label></td>
        </tr>
    </table>
}

一切看起来都很好,甚至还有智能感知功能。但浏览器中的输出如下所示:

代码语言:javascript
复制
Omega.UI.WebMvc.Helpers.BeginViewHelper+MyView { 


test

 } 

这是我的辅助方法:

代码语言:javascript
复制
namespace Omega.UI.WebMvc.Helpers
{
    public static class BeginViewHelper
    {
        public static IDisposable BeginView(this HtmlHelper helper)
        {
            helper.ViewContext.Writer.Write("<div data-bind=\"preventBinding: true\">");
            helper.ViewContext.Writer.Write("<div data-viewId=\"test\">");

            return new MyView(helper);
        }

        class MyView : IDisposable
        {
            private HtmlHelper _helper;

            public MyView(HtmlHelper helper)
            {
                this._helper = helper;
            }

            public void Dispose()
            {
                this._helper.ViewContext.Writer.Write("</div>");
                this._helper.ViewContext.Writer.Write("</div>");
            }
        }
    }
}

并且我已经在~/Views/web.config中注册了名称空间

代码语言:javascript
复制
 <add namespace="Omega.UI.WebMvc.Helpers" />
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-01-09 21:26:11

您不能返回MvcHtmlString。相反,您应该向编写器编写超文本标记语言,并返回实现IDisposable的类,在调用期间,Dispose将编写超文本标记语言的结束部分。

代码语言:javascript
复制
public static class BeginViewHelper
{
    public static IDisposable BeginView(this HtmlHelper helper, string viewId)
    {
        helper.ViewContext.Writer.Write(string.Format("<div id='{0}'>", viewId));

        return new MyView(helper);
    }

    class MyView : IDisposable
    {
        private HtmlHelper helper;

        public MyView(HtmlHelper helper)
        {
            this.helper = helper;
        }

        public void Dispose()
        {
            this.helper.ViewContext.Writer.Write("</div>");
        }
    }
}

如果你有更复杂的结构,你可以尝试使用TagBuilder:

代码语言:javascript
复制
TagBuilder tb = new TagBuilder("div");
helper.ViewContext.Writer.Write(tb.ToString(TagRenderMode.StartTag));
票数 20
EN

Stack Overflow用户

发布于 2013-01-09 21:52:31

Slawekcorrect answer,但我想我可以用我的经验补充一下。

我想创建一个helper来在页面上显示小部件(几乎类似于jQuery的小部件,带有标题栏和内容部分)。对…有影响的事物:

代码语言:javascript
复制
@using (Html.BeginWidget("Widget Title", 3 /* columnWidth */))
{
    @* Widget Contents *@
}

MVC源代码使用了与Slawek发布的类似的东西,但我觉得将开始标记放在helper中,将结束标记放在实际对象中并不“整洁”,也没有将问题放在正确的位置。如果我想改变外观,我现在在两个地方这样做,而不是我认为是一个合乎逻辑的地方。因此,我想出了以下几点:

代码语言:javascript
复制
/// <summary>
/// Widget container
/// </summary>
/// <remarks>
/// We make it IDIsposable so we can use it like Html.BeginForm and when the @using(){} block has ended,
/// the end of the widget's content is output.
/// </remarks>
public class HtmlWidget : IDisposable
{
    #region CTor

    // store some references for ease of use
    private readonly ViewContext viewContext;
    private readonly System.IO.TextWriter textWriter;

    /// <summary>
    /// Initialize the box by passing it the view context (so we can
    /// reference the stream writer) Then call the BeginWidget method
    /// to begin the output of the widget
    /// </summary>
    /// <param name="viewContext">Reference to the viewcontext</param>
    /// <param name="title">Title of the widget</param>
    /// <param name="columnWidth">Width of the widget (column layout)</param>
    public HtmlWidget(ViewContext viewContext, String title, Int32 columnWidth = 6)
    {
        if (viewContext == null)
            throw new ArgumentNullException("viewContext");
        if (String.IsNullOrWhiteSpace(title))
            throw new ArgumentNullException("title");
        if (columnWidth < 1 || columnWidth > 12)
            throw new ArgumentOutOfRangeException("columnWidth", "Value must be from 1-12");

        this.viewContext = viewContext;
        this.textWriter = this.viewContext.Writer;

        this.BeginWidget(title, columnWidth);
    }

    #endregion

    #region Widget rendering

    /// <summary>
    /// Outputs the opening HTML for the widget
    /// </summary>
    /// <param name="title">Title of the widget</param>
    /// <param name="columnWidth">Widget width (columns layout)</param>
    protected virtual void BeginWidget(String title, Int32 columnWidth)
    {
        title = HttpUtility.HtmlDecode(title);

        var html = new System.Text.StringBuilder();

        html.AppendFormat("<div class=\"box grid_{0}\">", columnWidth).AppendLine();
        html.AppendFormat("<div class=\"box-head\">{0}</div>", title).AppendLine();
        html.Append("<div class=\"box-content\">").AppendLine();

        this.textWriter.WriteLine(html.ToString());
    }

    /// <summary>
    /// Outputs the closing HTML for the widget
    /// </summary>
    protected virtual void EndWidget()
    {
        this.textWriter.WriteLine("</div></div>");
    }

    #endregion

    #region IDisposable

    private Boolean isDisposed;

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    public virtual void Dispose(Boolean disposing)
    {
        if (!this.isDisposed)
        {
            this.isDisposed = true;
            this.EndWidget();
            this.textWriter.Flush();
        }
    }

    #endregion
}

然后,这使得我们的助手更加清晰(并且在两个地方没有UI代码):

代码语言:javascript
复制
public static HtmlWidget BeginWidget(this HtmlHelper htmlHelper, String title, Int32 columnWidth = 12)
{
  return new HtmlWidget(htmlHelper.ViewContext, title, columnWidth);
}

然后我们可以像我在这篇文章的顶部所做的那样使用它。

票数 8
EN

Stack Overflow用户

发布于 2013-01-09 21:24:48

asp.net mvc的BeginForm方法返回MvcForm类的IDisposable实例。如果您深入查看asp.net mvc code on codeplex,您可以查看asp.net mvc团队是如何开发此功能的。

看看这些链接:

MvcForm类(IDisposable) http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/8b17c2c49f88#src/System.Web.Mvc/Html/MvcForm.cs

表单扩展(用于html帮助器) http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/8b17c2c49f88#src/System.Web.Mvc/Html/FormExtensions.cs

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14236017

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档