Snake Eyes
Snake Eyes

Reputation: 16764

Nesting multiple labels and inputs inside form tag using HtmlHelper in ASP.NET MVC 3

How do I nest multiple labels and inputs inside form tag with HtmlHelper in ASP.NET MVC3?

My code is below:

public static string GenerateFormForContact(this HtmlHelper helper, string method, string action, bool includeMailTag)
{
    //form tag
    TagBuilder form = new TagBuilder("form");
    form.Attributes.Add("action", action);
    form.Attributes.Add("method", method);

    //label and input tag

    TagBuilder labelClientName = new TagBuilder("label");
    labelClientName.Attributes.Add("for", "clientName");
    TagBuilder inputClientName = new TagBuilder("input");
    inputClientName.Attributes.Add("name", "clientName");
    inputClientName.Attributes.Add("type", "text");
    inputClientName.Attributes.Add("placeholder", "Your name");
    inputClientName.Attributes.Add("required", "required");

    //how to insert inside form

    TagBuilder labelEmailName = new TagBuilder("label");
    labelEmailName.Attributes.Add("for", "emailName");
    TagBuilder inputEmailName = new TagBuilder("input");
    inputEmailName.Attributes.Add("name", "emailName");
    inputEmailName.Attributes.Add("type", "email");
    inputEmailName.Attributes.Add("placeholder", "Your mail");
    inputEmailName.Attributes.Add("required", "required");

    //how to insert again inside form the second label and input

    //how to insert again inside form the n-th label and input 
    return form.ToString(TagRenderMode.Normal);
}

Upvotes: 3

Views: 8002

Answers (2)

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79979

If you want to enclose labelEmailName, inputEmailName and other elements (TagBuilder's) within the already-created form or any other TagBuilder use TagBuilder.InnerHtml Like this:

form.InnerHtml += labelEmailName.ToString();
form.InnerHtml += inputEmailName.ToString();

Upvotes: 13

kamranicus
kamranicus

Reputation: 4415

This is not an answer but a suggestion. Any reason not to use a Razor helper or Partial for this?

I wrote this in a text editor, so it probably has some incorrect methods but you get the idea:

@helper GenerateFormForContact(string method, string action, bool includeMailTag) {
   <form action="@action" method="@method">
      @Html.Label("some label")
      @Html.Textbox("clientName", null, new { placeholder = "Your name", required = "required" })

      @Html.Label("some label")
      <input type="email" name="emailName" placeholder="Your mail" required="required" />      
   </form>
}

Much cleaner IMHO. A Partial would look almost exactly the same except you'd pass in a model or use ViewData.

Upvotes: 4

Related Questions