Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Assuming I understand you correctly it sounds like you should be using a UserControl.</p> <p>Basically create a UserControl.ascx file (and VS will generate the UserControl.designer.cs and code-behind classes for you). Then put your input fields in there with no special attributes, like so:</p> <p>(Note that I prefer HtmlControls to WebControls, they give cleaner markup and don't muddy things. I suggest you give them a try):</p> <pre><code>&lt;%@ Control blargh %&gt; &lt;label for="&lt;%= Street.ClientID %&gt;"&gt;Street address&lt;/label&gt; &lt;input type="text" runat="server" id="Street" /&gt; &lt;br /&gt; &lt;label for="&lt;%= City.ClientID %&gt;"&gt;Town / City&lt;/label&gt; &lt;input type="text" runat="server" id="City" /&gt; &lt;br /&gt; &lt;!-- etc --&gt; </code></pre> <p>Note how I'm not messing with the <code>id=""</code> attribute of the input controls. Now just register it in your web.config:</p> <pre><code>&lt;add tagPrefix="foo" tagName="Address" src="~/Controls/Address.ascx" /&gt; </code></pre> <p>Then in each page that needs an address form (assuming your UserControl is called AddressControl)</p> <pre><code>&lt;%@ Page blargh %&gt; &lt;p&gt;Enter your address details below:&lt;/p&gt; &lt;foo:Address runat="server" id="Address" /&gt; </code></pre> <p>Then in your page's code-behind you can just do this:</p> <pre><code> public override void OnLoad(Object sender, EventArgs e) { if( Page.IsPostBack ) { Validate(); if( Page.IsValid ) { // get values from a POST String street = this.Address.Street.Value; String city = this.Address.City.Value; // and so on } } else { // set values if you're retrieving data from a DB or something this.Address.Street.Value = "123 Fake Street"; this.Address.City.Value = "Frying Pan City"; } } </code></pre> <p>Note how I used the "&lt;%= Street.ClientID %>"-thing. ASP.NET will automatically generate the control names and IDs based on the control's parent name (and so on, recursively). So the actual HTML input will be rendered like this:</p> <pre><code>&lt;label for="Address.Street"&gt;Street address&lt;/label&gt; &lt;input type="text" name="Address_Street" id="Address.Street" /&gt; </code></pre> <p>Note this design and practice only applies to WebForms. ASP.NET MVC is completely different again.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload