使用ASP.NET MVC 3中的HtmlHelper在表单标记中嵌套多个标签和输入

时间:2012-02-01 14:18:59

标签: c# asp.net asp.net-mvc-3

如何在ASP.NET MVC3中使用HtmlHelper在窗体标记内嵌套多个标签和输入?

我的代码如下:

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);
}

1 个答案:

答案 0 :(得分:13)

如果您想将labelEmailNameinputEmailName和其他元素(TagBuilder)包含在已创建的表单中或任何其他TagBuilder使用{{3}像这样:

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