Search code examples
.netasp.netajaxuser-controlsascx

.NET website: Get the output of .ascx from jQuery


In MVC .NET application we can easily use PartialView to print the output of an ASCX file.

For example, I have Book.ascx file, I could have this in the controller

public ActionResult Book(int id)
{
  BookModel model = new BookModel() { bookId = id };
  return PartialView("Book", model);
}

which returns the output of Book.ascx

Is there any way we can do this in a normal .NET website?

I want to be able to use it with AJAX, eg.
When an Update button is clicked, replace the content of <div id="book123"> with the output of /Book.ascx?id=123

Is that possible?

I am looking for something like this

$.get('Book.ascx?id=123', function(data) {
  $("#book123").html(data);
});

But that won't work because you can't call Book.ascx directly...

Thanks in advance


Solution

  • well, it is doable, but not pretty :)

    you could instantiate your control, and instead of passing the key via QueryString, do it via exposed property:

    var ctrl = new BookModel();
    ctrl.BookID = "book123";
    

    than you could render the HTML out of it with something like

    private string renderControl(Control ctrl)
    {
      System.Text.StringBuilder sb = new System.Text.StringBuilder();
      System.IO.StringWriter tw = new System.IO.StringWriter(sb);
      System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
      ctrl.RenderControl(hw);
      return sb.ToString();
    }
    

    than you would pass that html back via your service and insert into the div etc..