1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Victor Form markup does not work eg. Html.BeginFrom, Ajax.BeginForm, Html.TextBox. I'm using Umbraco 7, however the markup works fine in umbraco view, it does not work only in the helper.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.