不要使用 ASP.NET AJAX 页面方法从客户端 AJAX 调用返回数据,而是尝试使用 ASP.NET HTTP 处理程序,因为它可以让您更好地控制通过 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" />
更新:
您可以使用PlaceHolder 的ID 而不是在您的jQuery 选择器中使用class 名称,我最初建议不要这样做,因为在ASP 中使用母版页时它会受到名称修改的影响。网。无论如何,您可以使用 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);
注意:我希望尽可能避免使用尖括号 (<%= %>) 表示法。