9

The following asp.net side code of control:

<asp:TextBox runat="server" ID="LimitTextBox" Text="20" ClientIDMode="Static" />

Generates such HTML-code:

<input name="ctl11$ctl00$ctl02$TeamPlayerSelector$LimitTextBox" 
    type="text" value="20" id="LimitTextBox">

ID attribute - as is required, but how can I remove 'name' attribute? It is not required for me and is also too long to transfer it to user browser.

How can I prevent 'name' attribute generation? Thanks

P.S. I work under ASP.NET 4.0

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Budda
  • 18,015
  • 33
  • 124
  • 206
  • i dont think you can , its names like that when you enter it in a contenct place holder , if you want pure HTML use ASP.net MVC – Saif al Harthi Dec 12 '10 at 22:36
  • or 1. don't use server controls 2. create your own filters to clean up the html – Pauli Østerø Dec 12 '10 at 22:38
  • 3
    Are you sure you don't need the `name`? The value doesn't get sent back to the server on POST? If that's not the case...why not render a JavaScript variable instead? – Nick Craver Dec 12 '10 at 22:38
  • 2
    @nick good point, id is only for client side DOM manipulation... name is required for the browser to actually post the content. – Pauli Østerø Dec 12 '10 at 22:39

6 Answers6

7

create a Filter (class that inherits from Stream), assign it to your HttpContext.Response.Filter attribute, and in it you would overwrite the Write method, to remove all the name-tags from the generated html :)

See this page for more information http://msdn.microsoft.com/en-us/library/system.web.httpresponse.filter.aspx

Update

Looking at the sourcecode for TextBox it reveals that Name is actually added to the Attributes-list during render, so it should be possible to interfere with the rendering of the TextBox class and prevent this attribute from being added. This should do

public class NoNamesTextBox : TextBox
{
    private class NoNamesHtmlTextWriter : HtmlTextWriter
    {
        public NoNamesHtmlTextWriter(TextWriter writer) : base(writer) {}

        public override void WriteAttribute(string name, string value, bool fEncode)
        {
            if (name.Equals("name", StringComparison.OrdinalIgnoreCase)) return;

            base.WriteAttribute(name, value, fEncode);
        }
    }

    protected override void Render(HtmlTextWriter writer)
    {
        var noNamesWriter = new NoNamesHtmlTextWriter(writer);

        base.Render(noNamesWriter);
    }
}

Update once more

How could i forget! You don't even need to subclass your textbox. In asp.net you can define which HtmlTextWriter type you want to use per control, so you can just configure that every TextBox control should use an instance of your own NoNamesHtmlTextWriter like this

<browsers>
  <browser refID="Default">
    <controlAdapters>
      <adapter 
        controlType="System.Web.UI.WebControls.TextBox"
        adapterType="NoNamesTextBoxAdapter" 
      />
    </controlAdapters>
  </browser>
</browsers>

public class NoNamesTextBoxAdapter : ControlAdapter
{
    private class NoNamesHtmlTextWriter : HtmlTextWriter
    {
        public NoNamesHtmlTextWriter(TextWriter writer) : base(writer) { }

        public override void WriteAttribute(string name, string value, bool fEncode)
        {
            if (name.Equals("name", StringComparison.OrdinalIgnoreCase)) return;

            base.WriteAttribute(name, value, fEncode);
        }
    }

    protected override void Render(HtmlTextWriter writer)
    {
        var noNamesRender = new HtmlTextWriter(writer);
        base.Render(noNamesRender);
    }
}
Pauli Østerø
  • 6,878
  • 2
  • 31
  • 48
  • the 3rd update - is good suggestion. I would add: we would better have a sub-class for NoNameTextBox, and use 'NoNmaesTextBoxAdapter' for 'NoNameTextBox' only. – Budda Dec 17 '10 at 17:02
  • IMO thats double work... if you're subclassing the TextBox anyway, why not just override Render to use the NoNamesHtmlTextWriter in there instead? – Pauli Østerø Dec 17 '10 at 19:22
  • I tried the NoNamesHtmlTextWriter and doesn't seem to work. For me, the WriteAttribute never gets called because my TextBox has zero attributes (the AttributeCollection is empty). I don't know what I'm doing wrong, I'm using .NET 4.0 – Shankar May 31 '11 at 21:58
  • 1
    I overrode the OnAttributeRender method of the NoNamesHtmlTextWriter and returned "false" for the "name" attribute. That worked. – Shankar May 31 '11 at 23:18
  • I had the same problem as @Shankar so used `OnAttributeRender`. In the end it turned out I required the `name` attribute but it had to be the same value as the id, so I overrode `AddAttribute` and changed the name value. – Tim B James Nov 24 '11 at 14:03
3

For some unknown reason the WriteAttribute override didn't work. I replaced it with:

public override void AddAttribute(HtmlTextWriterAttribute key, string value)
{
   if (key == HtmlTextWriterAttribute.Name) return;
   base.AddAttribute(key, value);
}         

And it worked like a charm. Also if you just need a custom Name you can just override the UniqueID property:

public class MyCustomControl : TextBox
    {

        public override string UniqueID
        {
            get
            {
                //return base.UniqueID;
                return "test123";
            }
        }


    }

Thanks for your help!

JohnWinner
  • 41
  • 1
  • 3
2

Setting EnableViewState="False" will slim down the name. You can also make a class that inherits the Textbox Control and override the Render procedure to not include the name.

Public Class CustomTextBox
    Inherits TextBox
    Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
        MyBase.Render(writer)
        'Simplified rendering of control...
        writer.WriteLine("<input type='text' id='" & MyBase.ClientID & "'>")        
    End Sub
End Class

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     Dim MyCustomTextBox As New CustomTextBox
     form1.Controls.Add(MyCustomTextBox)
End Sub

Alternatively, if you don't want to have to add the control at run-time, you can make your CustomTextBox as a ServerControl so that you can add it at design time.

NoAlias
  • 9,218
  • 2
  • 27
  • 46
  • 1
    Good point for subclassing the TextBox. I updated my answer as well for this approach but it should be more robust to filter the name attribute away from the actual rendering than trying to completely hijack it. – Pauli Østerø Dec 12 '10 at 23:13
  • 3
    "Setting EnableViewState="False" will slim down the name" - this doesn't work – Budda Dec 17 '10 at 16:59
1

what ASP.Net controls render in name attributes, comes from UniqueID property. It's not necessarily good idea to override it, since ASP.NET uses that to locate control on postback to route postback data & events. However, if you are sure it is ok in your scenario, you certainly can override UniqueID property following @Pauli Østerø's answer. Have fun!

Skorpioh
  • 1,355
  • 1
  • 11
  • 30
0

I think better is to change name property to same like ID is..

Just try bellow by using Jquery on document.ready(function(){})

document.ready(function(){
  $.each($('div').children(), function() {
        $(this).attr("name",$(this).attr("id"));
  });
});
Imran Athar
  • 469
  • 5
  • 8
0

You can override the name property and return whatever you want (http://referencesource.microsoft.com/#System.Web/xsp/system/Web/UI/HtmlControls/HtmlInputControl.cs).

g.breeze
  • 1,940
  • 19
  • 24