-2

我有一个 Table 对象,我在后面的代码中创建并填充了它。由于各种原因,必须以这种方式完成。

我从客户端通过 AJAX 调用 WebMethod 以从下拉列表中发送一个变量,然后将表填充到后面代码中的静态方法中。我需要将表格放入 ASP.Net PlaceHolder。我不能从静态方法调用 PlaceHolder。

4

1 回答 1

2

尝试使用 ASP.NET HTTP 处理程序,而不是使用 ASP.NET AJAX 页面方法从客户端 AJAX 调用返回数据,因为它可以让您更好地控制通过 HTTP 标头返回的内容,而不必对 ASP.NET AJAX 页面方法调用的结果进行编码,如下所示:

public class GetHtmlHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // Grab the drop down list variable value from the query string

        // Use controls to build table or do it via StringWriter

        // Create a table row with three cells in it
        TableRow theTableRow = new TableRow();
        for (int theCellNumber = 0; theCellNumber < 3; theCellNumber++)
        {
            TableCell theTableCell = new TableCell();
            tempCell.Text = String.Format("({0})", theCellNumber);
            theTableRow.Cells.Add(theTableCell);
        }

        // Create writers to render contents of controls into
        StringWriter theStringWriter = new StringWriter();
        HtmlTextWriter theHtmlTextWriter = new HtmlTextWriter(theStringWriter);

        // Render the table row control into the writer
        theTableRow.RenderControl(theHtmlTextWriter);

        // Return the string via the StringWriter
        context.Response.Write(theStringWriter.ToString());
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

现在在客户端,使用 jQuery.ajax()函数调用 HTTP 处理程序,如下所示:

$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "PATH_TO_HANDLERS/GetHtmlHandler.ashx?id=YOUR_DROP_DOWN_VALUE",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            // Select the placeholder control by class here and put HTML into it
            $('.ThePlaceHolder').html(result);
        }
    });
}); 

注意:上述选择器要求您向控件添加CssClass属性,如下所示:PlaceHolder

<asp:PlaceHolder id="PlaceHolder1" runat="server" CssClass="ThePlaceHolder" />

更新:

除了class在 jQuery 选择器中使用名称之外,您还可以使用 的IDPlaceHolder我最初建议不要这样做,因为在 ASP.NET 中使用母版页时它会受到名称修改的影响。无论如何,ClientIDMode您可以使用该属性,如下所示:

<asp:PlaceHolder id="PlaceHolder1" runat="server" ClientIDMode="Static" />

现在您的 jQuery 选择器将如下所示:

// Select the placeholder control by ID here and put HTML into it
$('#<%= PlaceHolder1.ClientID %>').html(result);

注意:我希望尽可能避免使用尖括号 ( <%= %>) 表示法。

于 2013-12-11T16:26:07.747 回答