简体   繁体   中英

RenderControl in HtmlTextWriter - InvalidOperationException

I would like to render a Control object which is just created on the fly when the user send a postback request. To do so, I use the code below:

StringBuilder sb = new StringBuilder();
HtmlTextWriter ht = new HtmlTextWriter(new StringWriter(sb));
Rating r = new Rating("r", 5, 3, No, Big);
r.RenderControl(ht);

which unfortunately yields to an InvalidOperationException at the last line and with the following error:

The page can not be null. Make sure that this operation is performed in the context of an ASP.NET request.

I probably misunderstood the way I should use this RenderControl method, and I hope you can help me with my problem.

Thank you, David

It doesn't look like you're attaching your new Rating control to your Page control before attempting to render it.

From the MSDN docs for RenderControl , the internals of the call are going to be looking for the enclosing Page, and performing some activities based on the Page object's settings.

You might add a placeholder in your page and insert the Rating control there before attempting to render it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM