1

i have the following Problem:

I want to know if it is possible to modify default html helper methods, e.g. the Html.BeginForm() method.

I know that i can write a custom helper method where i can add some stuff, but some of them have alot of overloaded functions.

then only thing i would need is, that you can add some custom html string "after" the element was rendered

e.g.:

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

and after the

<form></form>

i would like to render a validation script, or something else, lets say jQuery validator:

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

since i dont want to do that over and over again (maybe i could forget it once..) it would be nice to modify the default Html helper.

If it is not possible i just might have to write my own BeginForm or a wrapper for the EndForm helper :/

4

3 回答 3

2

As a very basic starting point, you could use something like this:

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

You'd either need to add the namespace in your view or add it to the web.config file in your Views folder. After that, you can use it like so:

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

This works for me here but you'd certainly need to customise it to fit your needs, especially as you'll likely want to pass additional parameters to Html.BeginForm().

于 2012-08-07T14:36:46.930 回答
1

You may be able to write your own Extension method do this. Get the code of the BeginForm method from Codeplex.(The MVC3 source code is open source :) ) and make relevant updates to that to render the form like you want.

The code is available in the FormExtensions.cs class under the System.Web.MVC Project. Look for the FormHelper method which is being called from the BeginForm Overrides.

于 2012-08-07T14:07:01.810 回答
0

It is not possible. You'll have to do your own helpers.

于 2012-08-07T14:00:47.070 回答