Load ascx via jQuery

10,763

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

Solution 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();
}

Solution 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.

Share:
10,763
Admin
Author by

Admin

Updated on June 15, 2022

Comments

  • Admin
    Admin almost 2 years

    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.

  • Admin
    Admin over 13 years
    i'm developing web applicatiob CMS like. i need to call some part of my application as ascx file. i don't want to postback the page. is there a better way to do that? i dont want to load all part too.
  • Justin Niessner
    Justin Niessner over 13 years
    @Raika - If you really want to do things the right way, you'll make your page support ASP.NET WebForms AJAX (UpdatePanel, etc.) and make your controls compatible with that. That would allow you to load things dynamically via AJAX.
  • Vadim
    Vadim over 13 years
    @Raika, create an ashx handler that will do the same thing Emmett suggested and instead of a ViewPage object create a Page object. You won't need the ViewDataDictionary either.
  • Admin
    Admin over 13 years
    thanks. can you give me more link about web parts or complete tutorial for web parts?
  • Vadim
    Vadim over 13 years
    @Raika You can create ashx handlers in WebForms. I just posted a solution.
  • Vadim
    Vadim over 13 years
    @Raika Yes just go Add->New Item->Generic Handler
  • Justin Niessner
    Justin Niessner over 13 years
    @Raika - The last link I posted has links to the appropriate pages on MSDN. Unfortunately Web Parts can get fairly complex so you'll have to do a bit of reading.
  • Vadim
    Vadim over 13 years
    @Raika no worries. I'm also assuming emmett's solution works :-)
  • Admin
    Admin over 13 years
    @Yads. thanks. I'm update question. please help me with this too.
  • Vadim
    Vadim over 13 years
    @Raika, try the included ajax call.
  • Vadim
    Vadim over 13 years
    @Raika, try the updated RenderPartialToString, if that doesn't work. You may be SOL if you want to keep using server controls in your ascx. If you want to switch your ascx to either html, or using server tags you should be fine.
  • Admin
    Admin over 13 years
    i,m getting Error executing child request for handler 'System.Web.UI.Page'. but any way thank for your help and i think is better to work on some other solution instead this.
  • ahmad molaie
    ahmad molaie almost 8 years
    @Raika is this finally worked with asp.net controls on an general ascx?
  • HaBo
    HaBo about 5 years
    How do you pass params to RenderPartialToString("Foo.ascx") ?