当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Returning an HtmlTable to be written with ajax

问题描述:

I'd like to programmatically build an HtmlTable/Table in the code behind of a webservice and have it return as a string of HTML so that it can be written with JavaScript to the innerhtml of a span/div/whatever

Something similar to the following:

//webservice.amsx.cs Build the table, called by another/different method

protected string Table_Maker()

{

HtmlTable tbl = new HtmlTable();

HtmlTableCell cell = new HtmlTableCell();

HtmlTableRow row = new HtmlTableRow();

cell.InnerText = "WhateverText";

row.Cells.Add(cell);

tbl.Rows.Add(row);

return tbl.ToString();

}

//somepage.aspx write table to the div

function menuHelper(toplayer, toplayernumber)

{

var sublayertable;

var sublayerpostcompileID;

var toplayernumber;

menuHelper_Part1();

function menuHelper_Part1()

{

//replace ucMainMenu with ucMainMenu_pnlContent

sublayerpostcompileID = toplayer.replace("ucMainMenu", "ucMainMenu_pnlContent");

//Call the webmethod

webbernetz.MenuHelperWebService.Sub_Menu_Helper(toplayernumber, menuHelper_Part2);

}

function menuHelper_Part2(result){

//Write the result to the target area

document.getElementById(sublayerpostcompileID).innerHTML = result;

}

}

When I return it to the javascript the javascript simply writes "System.Web.UI.HtmlControls.HtmlTable".

How di I get it to write the actual table?

网友答案:

The only issue with your code is the use of "tbl.ToString()".

As noted in some of the other posts, you should Render the table control using an HtmlTextWriter to a StringBuilder object, which can then return a string value for your method. Something like this:

protected string Table_Maker() {
    HtmlTable tbl = new HtmlTable();
    HtmlTableCell cell = new HtmlTableCell();
    HtmlTableRow row = new HtmlTableRow();
    cell.InnerText = "WhateverText";
    row.Cells.Add(cell);
    tbl.Rows.Add(row);

    StringBuilder sb = new StringBuilder();
    using( StringWriter sw = new StringWriter( sb ) ) {
        using( HtmlTextWriter tw = new HtmlTextWriter( sw ) ) {
            tbl.RenderControl( tw );
        }    
    }    
    return sb.ToString();
}

That should return the HTML to be inserted into your page.

网友答案:

There is a RenderControl() method that you can call on any control. Or if you are not using HtmlTable to do anything with it other then building HTML then use HtmlTextWriter.

网友答案:

The problem here is that the HtmlTable.ToString method that you are using is not appropriate for what you want. 'ToString' returns a String that represents the current Object. In this case you have to Render the table first to an HTMLTextWriter and then you can use the method ToString.

网友答案:

Just use tbl.InnerHtml, instead of ToString

网友答案:

Sounds like you are making it more complicated than it needs to be. How about not using the HtmlTable object and just building a string containing the html you need to output.

分享给朋友:
您可能感兴趣的文章:
随机阅读: