在C#中的占位符中创建表单

时间:2013-02-19 16:46:32

标签: c# asp.net

StringBuilder str=new StringBuilder();
str.Append("<div style='font-style:oblique;font-size:24px;text-align:left;margin-bottom:25px;'>");
str.Append("Products");
str.Append("</div>");
str.Append("<div style='font-style:oblique;font-size:18px;text-align:right;margin-bottom:25px;'>");
str.Append("<asp:TextBox ID='txtSearch' runat='server'></asp:TextBox> &nbsp;&nbsp; <asp:Button ID='btbSearch' runat='server' Text='Search'/>");
str.Append("</div>");
str.Append("<table width='100%' border='1' cellpadding='0' cellspacing='0'>");

在第二个<div>中,我尝试创建一个文本框和一个按钮,并将它们添加到占位符中。当我使用浏览器控制台调试时,我在html代码中看到它们但它无法在浏览器中显示,它只是在浏览器上显示该表。有没有例子来处理这些案件?

3 个答案:

答案 0 :(得分:3)

<asp:标记完全是服务器端标记。它们将由ASP引擎转换为纯HTML标记。

通过直接将这些标记写入响应,您可以绕过ASP引擎将其重构为正确HTML的能力。当浏览器获取它们时,它不知道如何渲染它们,所以它只是忽略它们。

您应该将控件创建为对象,而不是字符串,例如:

TextBox txtSearch = new TextBox();
txtSearch.ID= "txtSearch";
placeHolder1.Controls.Add(txtSearch);

Button btbSearch = new Button();
btbSearch.ID = "btbSearch";
btbSearch.Text = "Search";
placeHolder1.Controls.Add(btbSearch);

或者,更好的是,您可以将该文本放在标记文件中,而不是使用后面的代码。

答案 1 :(得分:3)

很可能您不是生成ASPX页面以在服务器上呈现,而是将StringBuilder的输出发送到浏览器。由于asp:TextBox和类似的ASP.Net元素无法通过浏览器呈现,因此您在视图中看不到任何内容(也存在节点,因为它们不会使HTML完全无效)。

您希望生成<INPUT...>元素而不是asp:TextBox来查看浏览器中的输出。

注意:可能有更好的方法来实现您的目标(即客户端模板或视图中的常规渲染),但您需要先解决实际问题。

答案 2 :(得分:0)

您可以使用此类代码

var tableBody=""; // here you have to define the table body yourself

var form=
    new {
        method=@"get", // decide for your request method get/post
        action=@"http://www.google.com" // the page processes the request
    };

var html=@"
<div style='font-style: oblique; font-size: 24px; text-align: left; margin-bottom: 25px'>Products</div>

<div style='font-style: oblique; font-size: 18px; text-align: right; margin-bottom: 25px'>
    <form method='"+form.method+@"' action='"+form.action+@"'>
        <input id='txtSearch' name='txtSearch'>
        &nbsp;&nbsp;
        <input type='button' id='btbSearch' text='Search' onclick='this.parentNode.submit();'>
    </form>
</div>

<table width='100%' border='1' cellpadding='0' cellspacing='0'>"+tableBody+@"
</table>
";

html的固定部分代码不一定与StringBuffer一致。如果要动态生成html,请考虑使用LINQ。

您应该在代码的注释中做些什么。请注意,txtSearch不仅提供id,还提供name