Home >Backend Development >C#.Net Tutorial >Code example of asp.net method to dynamically generate HTML form
After testingThe
HtmlForm class under System.Web.UI.HtmlControls
is what we use in the traditional The Form form object used in asp.net is not suitable for dynamically generating Html code.
So I customized a simple HtmlForm
container control, which only requires a few lines of code. It seems that Asp.net still has great advantages in encapsulating Html elements. Microsoft has defined a large number of basic structures for us, which is 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); } } }
It is very simple to use, just use new, and 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, output the HTML code to the response stream.
form.RendControl(Writer);
Conclusion:
Dynamic generation of HTML forms is so simple and clear. I used to splice HTML myself and then write it. Being good at using the classes provided by the framework can effectively improve the opening efficiency and make the code more readable. Especially when making table controls, it will be helpful to make good use of the System.Web.UI.WebControls.Table
control.
The above is the detailed content of Code example of asp.net method to dynamically generate HTML form. For more information, please follow other related articles on the PHP Chinese website!