I have a user control that renders on .NET MVC pages using a TagPrefix / TagName registration. The attribute that calls it specifies to runat server, and specifies a couple of variable values that the user control's .ascx code uses as variables
e.g.
<%@ Register TagPrefix="UC" TagName="MyUserControl" Src="MyUserControlPathAndName.ascx" %>
. . .
<UC:MyUserControl runat="server" ID="MyID" ID2="MyID2" />
Then in the user control's .ascx, there is HTML, script, and code that uses the ID and ID2 variables.
What I want to do is to not code this tag into a .ascx file, but rather to keep my view very simple - just a call to an Html Helper, and in the HtmlHelper code, handle the use of this user control, but I'm kind of at a loss how to do so - is there a way inside an HTML helper to render tags that will then still get processed server side when the string generated by the HTML Helper is rendered? Or if not, then is there a way to do the rendering of the user control, (including passing it the ID and ID2 variables that it needs) from code when running my HTML Helper?
The method suggested here and here of calling ViewPage.RenderControl or Page.RenderControl does work, BUT I can't figure out how to pass in the ID and ID2 variables. I tried this
viewPage.ViewData = new ViewDataDictionary();
viewPage.ViewData.Add("ID", "MyID");
viewPage.ViewData.Add("ID2", "MyID2");
However, the code in the UserControl's .ascx that uses the ID2 property from the codebehind file did not see the value (presumably because it's not supposed to be a value in ViewData, but rather a value set on the UserControl class itself). Trying to figure out how I can set that property on the UserControl.
I think I may have found the answer here. Still validating. Will post it as the answer if it works.
This renders to string, using the variable set on the codebehind class (I didn't bother to set the ID variable as that seemed not to be used in the .ascx code, but rather just set an id on the control itself, but I think it could have been set without issues):