【问题标题】:Modify Html Helpers in ASP.NET MVC3 with razor使用 razor 在 ASP.NET MVC3 中修改 Html Helpers
【发布时间】:2023-03-29 15:35:01
【问题描述】:

我有以下问题:

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

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

那么我唯一需要的是,您可以在元素渲染“之后”添加一些自定义 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 助手的包装器:/

【问题讨论】:

    标签: c# asp.net-mvc-3 razor html-helper


    【解决方案1】:

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

    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】:

    您可以编写自己的扩展方法来做到这一点。从 Codeplex 获取 BeginForm 方法的代码。(MVC3 源代码是 open source :))并对其进行相关更新以呈现您想要的表单。

    代码在System.Web.MVC 项目下的FormExtensions.cs 类中可用。查找从 BeginForm Overrides 调用的 FormHelper 方法。

    【讨论】:

    • 感谢您的信息,我接受了 John H 的回答,因为他费心发布示例,但我没有想到 .NET 本身可以是开源的,因此浏览来源那里:)
    • 没问题。很高兴你能弄清楚。 John 值得 +15,因为他发布了一些代码 :)
    【解决方案3】:

    这是不可能的。你必须自己做帮手。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 2012-06-26
      • 1970-01-01
      • 2012-04-10
      • 2017-07-08
      • 2013-08-05
      相关资源
      最近更新 更多