我在后面的代码中有以下内容:
[WebMethod]
public static string GenerateHtml(string id)
{
//return id;
DataView vwMain2;
try
{
DbProviderFactory dbf = DbProviderFactories.GetFactory();
using (IDbConnection con = dbf.CreateConnection())
{
string sSQL;
sSQL = "select top 20 " + ControlChars.CrLf
+ " ASSISTING_FILE_ID, DATE_ENTERED, CLIENT_CLAIM_NUM, PRIMARY_INSURED, PRIMARY_CLAIMANT, LOB_ID, FILE_STATUS, BRANCH_NAME," + ControlChars.CrLf
+ " OWNERS_FIRST_NAME, OWNERS_LAST_NAME, OWNERS_NAME, OWNERS_EMAIL, OWNERS_OFFICE_PHONE, OWNERS_FAX_PHONE, OWNERS_CELL_PHONE" + ControlChars.CrLf
+ " from vwFILES_DetailViewWithOwners" + ControlChars.CrLf
+ " where 1 = 1 " + ControlChars.CrLf;
//+ " where 1 = 1 and WEB_USER_ID = '" + Security.USER_ID.ToString() + "'" + ControlChars.CrLf;
using (IDbCommand cmd = con.CreateCommand())
{
cmd.CommandText = sSQL;
using (DbDataAdapter da = dbf.CreateDataAdapter())
{
((IDbDataAdapter)da).SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
da.Fill(dt);
vwMain2 = dt.DefaultView;
GridView2.DataSource = vwMain2;
GridView2.DataBind();
}
}
}
}
}
catch (Exception ex)
{
SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex.Message);
//lblError.Text = ex.Message;
}
}
我想循环遍历并以下列格式创建HTML表:
<table>
<tbody>
<tr>
<th>Column Header</th>
</tr>
<tr>
<td>Column Data</td>
</tr>
</tbody>
</table>
最好的方法是什么?我希望在生成HTML后返回它。
谢谢。
答案 0 :(得分:2)
我只是使用stringBuilder并在一些循环中手动拼凑HTML。
StringBuilder sb = new StringBuilder();
sb.append('<table><tbody>');
foreach(DataRow r in dt.Rows)
{
sb.append('<tr><th>' + r["ColumnHeader"] + '</th></tr>');
sb.append('<tr><th>' + r["ColumnData"] + '</th></tr>');
}
sb.append('</tbody></table>');
return sb.ToString();
答案 1 :(得分:2)
如果你想把它称为WebService(例如:用于jQuery ajax调用),你有几个选择:
代码:
Control report;
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
Html32TextWriter hw = new Html32TextWriter(sw);
report = LoadControl("WebUserControl.ascx");
report.RenderControl(hw);
report = LoadControl("WebUserControl.ascx");
((IReportUserControl)report).LoadReport(); //Initialize the control
report.RenderControl(hw);
There is also a Stackoverflow post on the subject
安德鲁的答案是一种不同而简单的方法,也可以。
另外,值得一提的是,在做这类事情时,MVC可能会解决一系列问题。