Jquery使用通用处理程序加载usercontrol

时间:2012-01-03 11:25:14

标签: jquery asp.net

我需要使用jquery加载usercontrol。我创建了一个处理程序类并通过它加载了usercontrol。 jquery部分是:

$.ajax({
    type: "POST",
    url: "HandlerAdminManageDataSideMenu.ashx",
    contentType: "application/html; charset=utf-8",
    dataType: "html",
    success: function (data) {
        alert("success" + data);
        $(".admin_side_menu").append(data);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        debugger;
        alert("Error Occured!");
    }
});

我的处理程序文件如下:

Public Class HandlerAdminManageDataSideMenu
    Implements System.Web.IHttpHandler, IRequiresSessionState

    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        'context.Response.ContentType = "text/plain"
        'context.Response.Write("Hello World!")

        context.Response.ContentType = "text/html"
        context.Response.Write(RenderPartialToString("Shared\AdminManageDataSideMenu.ascx"))
    End Sub

    Private Function RenderPartialToString(ByVal controlName As String) As String
        Dim page As New Page()
        Dim control As Control = page.LoadControl(controlName)
        page.Controls.Add(control)

        Dim writer As New StringWriter()
        HttpContext.Current.Server.Execute(page, writer, False)

        Return writer.ToString()
    End Function

    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
End Class

HttpContext.Current.Server.Execute(page, writer, False)行引发错误:

  

执行处理程序'System.Web.UI.Page'

的子请求时出错

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

对RenderPartialToString函数稍作修改:

    Private Function RenderPartialToString(ByVal controlName As String) As String

    Dim page As New Page()
    Dim usercontrol As UserControl = CType(page.LoadControl(controlName), UserControl)

    usercontrol.EnableViewState = False
    Dim form As HtmlForm = New HtmlForm()
    form.Controls.Add(usercontrol)
    page.Controls.Add(form)

    Dim textWriter As StringWriter = New StringWriter()
    HttpContext.Current.Server.Execute(page, textWriter, False)
    Return textWriter.ToString()

End Function

参考链接:http://www.aspxtutorial.com/post/2011/01/02/Load-aspnet-web-user-control-using-jQuery-and-web-method.aspx

感谢所有回复。

答案 1 :(得分:0)

是的,可以使用.load()代替。 http://api.jquery.com/load/

“描述:从服务器加载数据并将返回的HTML放入匹配的元素中。”

我给你的链接中的样本:

$("#success").load("/not-here.php", function(response, status, xhr) {
  if (status == "error") {
    var msg = "Sorry but there was an error: ";
    $("#error").html(msg + xhr.status + " " + xhr.statusText);
  }
});