March 21st, 2008 admin
Coding client html of web-forms is not the easiest and not the most interesting part of developing a web-application. There are loads of ways of doing that. But the question is - which one is the right one? The html code should be semantyc, accessible and obvious for other developers. So I tried googling and found this article that seemed very interesting to me. How that could've been more obvious that fieldsets and labels should be used for developing web-forms? And by using CSS we could make the form look in many different ways!
Have a look at the following example:
<fieldset class="form-fieldset">
<label class="textbox surname">
<span>Surname</span>
<input name="surname" id="surname" type="text" />
</label>
</fieldset>
Now with a help of CSS we could access any element of this form. Very flexible. We could use as many fieldsets as we could wish. We could even have fieldsets inside fieldsets.
Alright. Later I started thinking how I could use that for simplify the way of creating asp.net web forms. So I created a class FieldSet
public class FieldSet : HtmlGenericControl
{
public FieldSet()
: base("fieldset")
{ }
public FieldSet(string strLegend)
: this()
{
HtmlGenericControl legend = new HtmlGenericControl("legend");
Controls.Add(legend);
legend.InnerText = strLegend;
}
// as an example I have created this simple method which allows add a new input text to the fieldset
public HtmlInputText AddInputText(string strLabel, string strCSSClass)
{
HtmlInputText txt = new HtmlInputText();
AddControl(strLabel, txt, strCSSClass);
return txt;
}
public HtmlInputText AddInputText(string strLabel)
{
return AddInputText(strLabel, null);
}
// this method is used for adding any web contol to the fieldset
public void AddControl(string strLabel, Control cntrl, string strCSSClass)
{
HtmlGenericControl label = new HtmlGenericControl("label");
Controls.Add(label);
label.Controls.Add(new LiteralControl("<span>" + strLabel + "</span>"));
if (strCSSClass != null)
label.Attributes["class"] = strCSSClass;
label.Controls.Add(cntrl);
cntrl.ID = ID + "_cntrl_" + Controls.Count.ToString();
label.Attributes["for"] = cntrl.ClientID;
}
public void AddControl(string strLabel, Control cntrl)
{
AddControl(strLabel, cntrl, null);
}
}
So now while developing another asp.net web-form I just could write the code:
.....
FieldSet fs = new FieldSet("Editing surname");
Controls.Add(fs);
HtmlInputText txtSurname = fs.AddInputText("Surname:", "surname");
.....
See? Just three lines of code.
Posted in asp.net, development, html | No Comments »