Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

asp.net - Load ascx via jQuery

Is there a way to load ascx file by jQuery?

UPDATE:

thanks to @Emmett and @Yads. I'm using a handler with the following jQuery ajax code:

 jQuery.ajax({
    type: "POST",  //GET
    url: "Foo.ashx",
    data: '{}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response)
    {
        jQuery('#controlload').append(response.d); // or response
    },
    error: function ()
    {
        jQuery('#controlload').append('error');
    }
 });

but I get an error. Is my code wrong?

Another Update : I am using

error: function (xhr, ajaxOptions, thrownError)
{
    jQuery('#controlload').append(thrownError);
}

and this is what i get :

Invalid JSON:
Test =>(this test is label inside my ascx)

and my ascx file after Error!!!

Another Update :

my ascx file is somthing like this:

<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true">
    <asp:ListItem>1</asp:ListItem>
    <asp:ListItem>2</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="Label1" runat="server">Test</asp:Label>

but when calling ajax i get this error in asp: :(

Control 'ctl00_ddl' of type 'DropDownList' must be placed inside a form tag with runat=server.

thanks to @Yads. but his solution only work with html tag.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Building off Emmett's solution

public class FooHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/html";
        context.Response.Write(RenderPartialToString("Foo.ascx"));
    }

    private string RenderPartialToString(string controlName)
    {
        Page page = new Page();
        Control control = page.LoadControl(controlName);
        page.Controls.Add(control);

        StringWriter writer = new StringWriter();
        HttpContext.Current.Server.Execute(page, writer, false);

        return writer.ToString();
    }

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

Use the following jquery request

jQuery.ajax({
    type: "POST",  //GET
    url: "Foo.ashx",
    dataType: "html",
    success: function (response)
    {
        jQuery('#controlload').append(response); // or response
    },
    error: function ()
    {
        jQuery('#controlload').append('error');
    }
 });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...