0

I have a method like this:

public MvcHtmlString RenderStuff(HtmlHelper<TModel> htmlHelper)
{
    TagBuilder div = new TagBuilder("div");

    //Dynamically add elements to form e.g.
    div.InnerHtml += System.Web.Mvc.Html.InputExtensions.TextBox(htmlHelper, "MyTextBox").ToHtmlString();


    return MvcHtmlString.Create(div.ToString());
}

It all works correctly but I can't work out how I can add a form around it within the method - that is to say that at this point in time I am adding the form in the view like so:

<% using (Html.BeginForm()) { %>

    <%=(ViewData["MyStuff"] as MyStuff).RenderStuff(Html)%>

<% } %>

I guess I am trying to do something like this but I am thinking that I will need to somehow render the form to the div and then append the textbox to the form...:

       using (htmlHelper.BeginForm())
        {
            div.InnerHtml += div.InnerHtml += System.Web.Mvc.Html.InputExtensions.TextBox(htmlHelper, "MyTextBox").ToHtmlString();

        }

Please don't suggest using TagBuilder("form") and then appending the items to that - I am using the MVC Client Validation and it seems to require using Html.BeginForm - If I can't figure out a way to do this I will leave the form in my view rather than spend time trying to hack the validation to make it work as it is working very nicely at the moment.

Any suggestion greatly appreciated, thanks in advance :-)

Cheers Rob

Rob
  • 10,004
  • 5
  • 61
  • 91

1 Answers1

1

I slept on this and had some clarity in the morning here is the answer for anyone who want's to do this in the future at all:

You can't return a string and then render it from the View - return void and render it in the method so that as you are rendering the htmlHelper ViewContext is current/relevant:

public void RenderStuff(HtmlHelper<TModel> htmlHelper)
{
    TagBuilder div = new TagBuilder("div");

    using(htmlHelper.BeginForm()){

       //Dynamically add elements to form e.g.
       div.InnerHtml += System.Web.Mvc.Html.InputExtensions.TextBox(htmlHelper, "MyTextBox").ToHtmlString();

       htmlHelper.ViewContext.HttpContext.Response.Write(div.ToString());

    }
}
Rob
  • 10,004
  • 5
  • 61
  • 91