Search code examples
asp.net-mvcrazorhtml-helperhtml.beginform

How to use built-in HTML helpers within a custom HTML helper?


I'm trying to use BeginForm in a helper razor function eg.

@helper Modal(string name)
{
<div id="@name">

    @using (Html.BeginForm("Add", "User", FormMethod.Post)) {
        <fieldset>
            @Html.Label("Name")
            @Html.TextBox("Name", new { @class = "text ui-widget-content ui-corner-all" })
            @Html.Label("Email")
            @Html.TextBox("Email", new { @class = "text ui-widget-content ui-corner-all" })

            <input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
        </fieldset>
    }
</div>
}

However I am getting an error:

@MyHelper.Modal("dialog-form")

It's due to Html... markup, without it it obviously works fine with only html.

What am I missing to make it working?

I have added @using System.Web.Mvc.Html; but it still does not recognise FormMethod.


Solution

  • Unfortunately declarative helpers which are defined in App_Code folder seems to inherit from System.Web.WebPages.HelperPage instead of System.Web.Mvc.WebViewPage from which the normal cshtml files inherit.

    It seems that the helper page also has a Html property but it's null.

    However, it seems that you can access all this helpers through PageContext.Page. Also you'll need to add some using statements (all the namespaces from the web.config which is located in the views folder) so you can access important extensions methods like Html.BeginForm.

    Here is a sample demo code:

    @using System.Web.Mvc
    @using System.Web.Mvc.Routing
    @using System.Web.Mvc.Html
    @using System.Web.Mvc.Ajax
    @using System.Web.Mvc.Razor
    @using System.Web.Optimization
    
    @helper MyCustomHelper()
    {
        var wvp = PageContext.Page as System.Web.Mvc.WebViewPage;
    
        var Html = wvp.Html;
        var Ajax = wvp.Ajax;
        var Url = wvp.Url;
        var ViewBag = wvp.ViewBag;
    
        // ... Helper code goes here ...
    
        @using (Html.BeginForm("Add", "User", FormMethod.Post))
    
        @Ajax.BeginForm ...
    
        @Url.Action ...
    
        // ...
    }
    

    Hope this helps.