ASP.NET how to Render a control to HTML?

前端 未结 3 1955
自闭症患者
自闭症患者 2020-11-27 18:18

I have any ASP.NET control. I want the HTML string how to do I get the HTML string of the control?

3条回答
  •  青春惊慌失措
    2020-11-27 19:13

    If your control is a web user control, this is how you can get to the HTML it emits from another page or handler:

    public void GetHtmlFromMySweetControl(HttpContext context)
    {
        HttpRequest httpRequest = context.Request;
        HttpResponse httpResponse = context.Response;
    
        string foo = httpRequest["foo"];
    
        Page pageHolder = new Page();
        string path = "~/usercontrols/MySweetControl.ascx";
        MySweetControl ctrl = (MySweetControl)pageHolder.LoadControl(path);
        ctrl.BindProducts(foo);
        pageHolder.Controls.Add(ctrl);
    
        StringWriter sw = new StringWriter();
        context.Server.Execute(pageHolder, sw, false);
        httpResponse.Write(sw.ToString());
    }
    

提交回复
热议问题