代码之家  ›  专栏  ›  技术社区  ›  r3bel

使用剃刀修改ASP.NET MVC3中的Html帮助程序

  •  1
  • r3bel  · 技术社区  · 13 年前

    我有以下问题:

    我想知道是否可以修改默认的html辅助方法,例如html.BeginForm()方法。

    我知道我可以写一个自定义的helper方法,在那里我可以添加一些东西,但其中一些方法有很多重载的函数。

    那么我唯一需要的就是,您可以在元素呈现之后添加一些自定义的html字符串

    例如:

    @using(Html.BeginForm("setDate", "DateController", new { DateId = Model.Date.Identifier }, FormMethod.Post, new { id = "setDateForm" })) {
        @* some input here... *@
    }
    

    <form></form>
    

    我想呈现一个验证脚本或其他东西,比如jQuery验证器:

    <script>$('#setDateForm').validate();</script>
    

    由于我不想一次又一次地这样做(也许我可以忘记一次…),修改默认的Html助手会很好。

    如果不可能,我可能只需要编写自己的BeginForm或EndForm帮助程序的包装器:/

    3 回复  |  直到 13 年前
        1
  •  2
  •   John H    13 年前

    作为一个非常基本的起点,您可以使用以下内容:

    namespace YourProject.Helpers
    {
        public static class HtmlHelperExtensions
        {
            public static IDisposable CustomBeginForm(this HtmlHelper helper, string html)
            {
                return new MvcFormExtension(helper, html);
            }
    
            private class MvcFormExtension : IDisposable
            {
                private HtmlHelper helper;
                private MvcForm form;
                private string html;
    
                public MvcFormExtension(HtmlHelper helper, string html)
                {
                    this.helper = helper;
                    this.form = this.helper.BeginForm();
                    this.html = html;
                }
    
                public void Dispose()
                {
                    form.EndForm();
                    helper.ViewContext.Writer.Write(this.html);
                }
            }
        }
    }
    

    您需要在视图中添加命名空间,或者将其添加到Views文件夹中的web.config文件中。之后,您可以这样使用它:

    @using (Html.CustomBeginForm("<p>test</p>")) {
        // Additional markup here
    }
    

    这对我来说很有效,但你肯定需要定制它以满足你的需求,尤其是当你可能想将额外的参数传递给 Html.BeginForm()

        2
  •  1
  •   Shyju    13 年前

    您可以编写自己的Extension方法来完成此操作。从Codeplex获取BeginForm方法的代码。(MVC3源代码为 open source :)),并对其进行相关更新,以按照您的意愿呈现表单。

    代码位于 FormExtensions.cs 下的类 System.Web.MVC 项目查找从BeginForm覆盖中调用的FormHelper方法。

        3
  •  0
  •   Sergei Rogovtcev    13 年前

    这是不可能的。你将不得不做你自己的助手。