load a user control programmatically in to a html text writer

后端 未结 3 661
执笔经年
执笔经年 2020-12-29 15:26

I am trying to render a user control into a string. The application is set up to enable user to use tokens and user controls are rendered where the tokens are found.

<
3条回答
  •  囚心锁ツ
    2020-12-29 16:14

    I've been using the following code provided by Scott Guthrie in his blog for quite some time:

    public class ViewManager
    {
        public static string RenderView(string path, object data)
        {
            Page pageHolder = new Page();
            UserControl viewControl = (UserControl) pageHolder.LoadControl(path);
    
            if (data != null)
            {
                Type viewControlType = viewControl.GetType();
                FieldInfo field = viewControlType.GetField("Data");
                if (field != null)
                {
                    field.SetValue(viewControl, data);
                }
                else
                {
                    throw new Exception("ViewFile: " + path + "has no data property");
                }
            }
    
            pageHolder.Controls.Add(viewControl);
            StringWriter result = new StringWriter();
            HttpContext.Current.Server.Execute(pageHolder, result, false);
            return result.ToString();
        }
    }
    

    The object data parameter, enables dynamic loading of data into the user control, and can be used to inject more than one variable into the control via an array or somethin similar.

    This code will fire all the normal events in the control.

    You can read more about it here

    Regards Jesper Hauge

提交回复
热议问题