简体   繁体   中英

Can RenderControl output WebControl markup instead of HTML markup?

I would like to leverage the asp.net WebControl classes (TextBox, CheckBoxList, Button, etc) to build a string that can be parsed into a Control using TemplateControl.ParseControl().

I am using the following code to output HTML from a WebControl:

TextBox control = new TextBox();
StringBuilder sb = new StringBuilder();
HtmlTextWriter objHtml = new HtmlTextWriter(new System.IO.StringWriter(sb));
control.RenderControl(objHtml);

This outputs:

"<input name=\"Phone\" type=\"text\" id=\"Phone\" />"

Is it possible to output the following instead?:

"<asp:Textbox name=\"Phone\" id=\"Phone\" runat=\"server\" />"

Why don't you store a string somewhere for each of the control types you need, then reference that by a key? That would only be a one time effort.

string ctrlMarkup =  GetMarkupFor("Textbox")

You probably want to change the Id and other properties, and you should be able to do that after instantiating and possibly casting it to it's specific type.

Or move parseControl into your getter and return a ready made control.

string id= "Button1";
string text = "Save";
Control tbx= GetControl("TextBox", id, text);

public Control GetControl(string type, string id, string text)
{
   Control ctrl;

   switch(type)
   {
      case: "TextBox"
      ctrl= (TextBox)TemplateControl.ParseControl("<asp:Textbox runat=\"server\" />");
      ((TextBox)ctrl).Id = id;
      ((TextBox)ctrl).Text = text;
      break;
   }

   return ctrl;
}

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