How can I use Html.BeginForm in a custom helper?

asp.net-mvc-3, c#, html-helper, razor

Solution

public static class HtmlExtensions
{
    public static void EditOrDelete(this HtmlHelper html)
    {
        using (html.BeginForm())
        {
            html.ViewContext.Writer.Write("additional fields");
        }
    }
}

and then:

@using namespace.CustomHelper
@{Html.EditOrDelete();}

emits:

<form action="/" method="post">additional fields</form>

Problem

So I am trying to convert this razor syntax in a .cshtml view into a helper extension in .cs. There is an awesome post on this by Darin here: https://stackoverflow.com/a/8187441/1026459. However, I am having some issues getting it to work. This is the plain markup ``` @using (Html.BeginForm("Restore", "GlobalCrud")) { @Html.Hidden("entityId", "Id") <input class="ui-icon ui-icon-power" type="submit" onclick="return confirm('Clicking OK will restore this record');" /> } ``` This is the extention ``` public static MvcHtmlString EditOrDelete(this HtmlHelper html) { var s = html.BeginForm(); return MvcHtmlString.Create(s + " additional fields " + "</form>"); } ``` This is the use: ``` @using namespace.CustomHelper @Html.EditOrDelete() ``` This is the output: ``` <form method="post" action="/Completed/Manage"> System.Web.Mvc.Html.MvcForm additional fields </form> ``` The helper extention for the most part produces what I need. However, I am uncertain how I should be converting this back to a proper html string. The return includes `System.Web.Mvc.Html.MvcForm` in the text. I am adding `" additional fields "` for brevity here because there is no issue there. The addition of `</form>` is there because I know that the normal `using` statement that goes with `@Html.BeginForm()` adds the `</form>` tag when it disposes. How can I properly return the form generated by `.BeginForm`?

Original source

Related problems