后面的ASP.net代码生成Web用户控件而不传递值

时间:2017-07-31 15:38:10

标签: c# asp.net user-controls dynamic-usercontrols

我有一个需要加载自定义webuser控件的函数,将一些值传递给它,然后获取此控件生成的HTML。

我有代码:

string renderedControl;
{
    var page = HttpContext.Current.Handler as Page;
    var ctrl = (ResponsiveImageFixedSize)page.LoadControl("~/PageControls/ResponsiveImageFixedSize/ResponsiveImageFixedSize.ascx");
    ctrl.Width = 600;
    ctrl.UploadedImage = upload;

    var sb = new StringBuilder();
    var tw = new StringWriter(sb);
    var hw = new HtmlTextWriter(tw);
    ctrl.RenderControl(hw);
    renderedControl = sb.ToString();
}

我得到的HTML是我期望的HTML,如果没有值传递给控件。在控件本身,如果我这样做:

protected void Page_Load(object sender, EventArgs e)
{
    Width.ToString().Log();

其中Log()是一个将值保存到数据库的可靠函数,显然没有执行此函数。

我在这里做得对吗?

1 个答案:

答案 0 :(得分:0)

解决了一下玩耍:

string renderedControl;
{
    var page = new Page();
    var ctrl = (ResponsiveImageFixedSize)page.LoadControl("~/PageControls/ResponsiveImageFixedSize/ResponsiveImageFixedSize.ascx");
    ctrl.Width = 600;
    ctrl.UploadedImage = upload;
    ctrl.OriginalImagePath = originalImagePath;
    ctrl.Alt = alt;
    page.Controls.Add(ctrl);
    var sw = new StringWriter();
    HttpContext.Current.Server.Execute(page, sw, false);
    renderedControl = sw.ToString();
}