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



我有以下问题:

我想知道是否可以修改默认的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 帮助程序的包装器:/

作为一个非常基本的起点,你可以使用这样的东西:

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);
            }
        }
    }
}

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

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

这在这里对我有用,但您当然需要对其进行自定义以满足您的需求,尤其是当您可能希望将其他参数传递给Html.BeginForm()时。

你可以编写自己的扩展方法来执行此操作。从 Codeplex 获取 BeginForm 方法的代码。(MVC3 源代码是开源:))并对其进行相关更新,以根据需要呈现表单。

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

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

最新更新