Introduction
This blog post will show you how to add and dynamically create ASP.NET Server Controls and place the controls into an HTML DIV
server tag. Create your ASP.NET web application [project] and integrate your required theme(template). As per your requirement, create a web form and design page layout and create a container div
with id="myFormContainer"
and div
as a server control-runat="server". In this
div going to add child div
, label
, textbox
, button
, etc. controls dynamically.
Create Dynamic ASP.NET Server Control
All controls list retrieved from "Controls
" json object (List
). You can create a json file and deserialize json object with C# class object, easily create number of controls dynamically with required attributes, e.g., Id
, text
, etc. You can also try to control list retrieved from database table.
Classes, Methods and Events
Step 1: Create Basic Classes
public class Control
{
public string ID { get; set; }
public string LabelText { get; set; }
}
public class ControlList
{
public List<control> Controls { get; set; }
}
Step 2: Controls List (Get from json Object or Database Table)
string json = @"{Controls:[{ID:'UserName', LabelText:'User Name'},
{ID:'EmailId', LabelText:'Email Address'},{ID:'Password', LabelText:'Password'},
{ID:'Phone', LabelText:'Phone Number'}]}";
var controls = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<controllist>(json);
Step 3: Create Method to Bind Controls
private void CreateControls(ControlList controls)
{
foreach (var control in controls.Controls)
{
HtmlGenericControl div = new HtmlGenericControl("div");
div.Attributes.Add("class", "form-group");
div.Controls.Add(new Label() { Text = control.LabelText,
AssociatedControlID = control.ID, CssClass = "col-md-2 control-label" });
HtmlGenericControl divInner = new HtmlGenericControl("div");
divInner.Attributes.Add("class", "col-md-10");
divInner.Controls.Add(new TextBox() { ID = control.ID, CssClass = "form-control" });
divInner.Controls.Add(new RequiredFieldValidator()
{ ControlToValidate = control.ID, CssClass = "text-danger",
ErrorMessage = "The user name field is required." });
div.Controls.Add(divInner);
Container.Controls.Add(div);
}
var button = new Button { ID = "btnClick", Text = "Create" };
button.Click += btnClick_OnClick;
Container.Controls.Add(button);
}
Step 4: Call CreateControl() Method on OnInit Event
override protected void OnInit(EventArgs e)
{
string json = @"{Controls:[{ID:'UserName', LabelText:'User Name'},
{ID:'EmailId', LabelText:'Email Address'},{ID:'Password', LabelText:'Password'},
{ID:'Phone', LabelText:'Phone Number'}]}";
var controls = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<controllist>(json);
CreateControls(controls);
}