Load ascx via jQuery

2019-01-17 01:54发布

问题:

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.

回答1:

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');
    }
 });


回答2:

public ActionResult Foo()
{
    return new ContentResult
    {
        Content = RenderPartialToString("Foo.ascx", null),
        ContentType = "text/html"
    };
}

//http://www.klopfenstein.net/lorenz.aspx/render-partial-view-to-string-asp-net-mvc-benchmark
public static string RenderPartialToString(string controlName, ViewDataDictionary viewData)
{
    ViewPage vp = new ViewPage();

    vp.ViewData = viewData;

    Control control = vp.LoadControl(controlName);
    vp.Controls.Add(control);

    StringBuilder sb = new StringBuilder();

    using (StringWriter sw = new StringWriter(sb))
    {
        using (HtmlTextWriter tw = new HtmlTextWriter(sw))
        {
            vp.RenderControl(tw);
        }
    }

    return sb.ToString();
}


回答3:

*.ascx files are rendered on the server side (inside of an *.aspx page), not the client side (where JavaScript is executed).

One option might be to create a blank *.aspx, put the user control on the *.aspx page, and then get that page via jQuery and dump the result on the page.

Edit

Based on your comment, I have another suggestion:

If you're developing a CMS style application, you should build your *.ascx controls so that they are compatible with the ASP.NET AJAX Toolkit. That will allow the users to add content to the page without doing a full refresh.

If you really want to make things nice for the user, you should check out Web Parts and ASP.NET AJAX as Web Parts were really designed so that users could customize the content on their pages.