Porco
Porco

Reputation: 4203

Can I force asp to set name the same as id

I need to process a form full of all sorts of different search controls, however these search controls are now inside a master page and so the id's were getting extra junk added in ('ct100$Body$TextBox_Postal' as opposed to 'TextBox_Postal').

I was able to fix this by setting ClientIDMode=CliendIDMode.Static, this works great as it doesn't try and include the namingcontainer in the id. I am confident that there will never be two of the same control on the page so this would work.

The problem is, when the form is posted back the controls are processed by names. The names are still of the 'ct1200$Body$..' format, so the processform function is unable to find any controls. Is there a way to get ASP to set the names in "Static" mode as well?

Upvotes: 9

Views: 10235

Answers (2)

Icarus
Icarus

Reputation: 63966

I don't think there's a way to set the name of the controls appropriately but you could alternatively change their names very easily using JQuery, if that's an option for you.

Example here

Some explanation:

  • Assuming you have markup like this:

    <div>
        <asp:textbox runat="server"  id="staticid1" />
        <asp:textbox runat="server"  id="staticid2" />
        <asp:textbox runat="server"  id="staticid3" />
    </div>
    

You could automatically change all of those control names to have the same names as their ids doing something like this on window.load:

 $.each($('div').children(), function() {
      $(this).attr("name",$(this).attr("id"));
   });

All you need in order to make that work is include JQuery; you could use Google's CDN: http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js

Upvotes: 13

rick schott
rick schott

Reputation: 21117

Short answer is no, you will have to override the rendering of the name attribute, example below from this question: ASP.NET: how to remove 'name' attribute from server controls?

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);
    }
}

Upvotes: 2

Related Questions