简体   繁体   English

RenderControl output WebControl 标记可以代替 HTML 标记吗?

[英]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().我想利用 asp.net WebControl 类(TextBox、CheckBoxList、Button 等)来构建一个可以使用 TemplateControl.ParseControl() 解析为控件的字符串。

I am using the following code to output HTML from a WebControl:我正在使用来自 WebControl 的 output HTML 的以下代码:

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?:是否可以改为 output 以下?:

"<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.您可能想要更改 Id 和其他属性,并且您应该能够在实例化并可能将其转换为特定类型之后执行此操作。

Or move parseControl into your getter and return a ready made control.或者将 parseControl 移动到你的 getter 中并返回一个现成的控件。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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