asp. net method of dynamically generating HTML form

  • 2021-09-16 06:34:48
  • OfStack

This paper illustrates the method of dynamically generating HTML form by asp. net. Share it for your reference, as follows:

After testing System.Web.UI.HtmlControls Under HtmlForm Class, the Form form object we used in the traditional asp. net, is not suitable for dynamically generating Html code.

So I customized a simple HtmlForm Container control, only a few lines of code. It seems that Asp. net has great advantages in encapsulating Html elements. Microsoft has defined a large number of infrastructures for us, which are easy to expand and use.


public class myHtmlForm:HtmlContainerControl
{
    public myHtmlForm(): base("form")
    {
      this.Attributes.Add("method", "post");
    }
    public string Action
    {
      set
      {
        Attributes.Add("action", value);
      }
    }
}

new, then add controls to the Controls collection.


myHtmlForm form = new myHtmlForm();
form.ID = "myform";
form.Action = "test.aspx";
HtmlInputHidden hidf= new HtmlInputHidden();
hidf.ID = hidf.Name = "hidden";
form.Controls.Add(hidf);

Finally, in View, the HTML code is output to the response stream.


form.RendControl(Writer);

Conclusions:

Dynamic generation of HTML forms is so simple and clear. I used to splice HTML myself, and then Write. Being good at using the classes provided by the framework can effectively improve the opening efficiency and make the code readable. Especially when doing table controls, make good use of System.Web.UI.WebControls.Table Control, it will be very helpful.

For more readers interested in asp. net, please check out the topics on this site: "Summary of asp. net Optimization Skills", "Summary of asp. net String Operation Skills", "Summary of asp. net File Operation Skills", "Summary of ES50net ajax Skills" and "Summary of asp. net Cache Operation Skills".

I hope this article is helpful to everyone's asp.net programming.


Related articles: