views:

40

answers:

2

I have a page that contains a user control.

Can i make an ajax request directly to the control?

I know I can make an ajax request to .aspx or .ashx; however, is it possible to go direct to the .ascx?

+1  A: 

In an ASP.NET MVC application yes:

public ActionResult Foo()
{
    return PartialView();
}

and then send the AJAX request:

$('#someDiv').load('/home/foo');

will load the Foo.ascx partial view inside a div.

In a classic ASP.NET WebForms application you will need to setup a generic handler that renders the contents of the user control into the response. Here's an example of a generic handler that could be used:

public class Handler1 : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        using (var writer = new StringWriter())
        {
            Page pageHolder = new Page();
            var control = (UserControl)pageHolder.LoadControl("~/foo.ascx");
            pageHolder.Controls.Add(control);
            context.Server.Execute(pageHolder, writer, false);
            context.Response.ContentType = "text/html";
            context.Response.Write(writer.GetStringBuilder().ToString());
        }
    }

    public bool IsReusable
    {
        get { return false; }
    }
}
Darin Dimitrov
m wrking on classic asp.netmeans not possible without setting up handler?
vakas
Either setting up a handler or an aspx page that contains only this control.
Darin Dimitrov
+1  A: 

You can make a simple ASPX page that contains nothing but the usercontrol.

SLaks
I'd say this is the preferred method.
Chris Lively