Can I force asp to set name the same as id

北慕城南 提交于 2019-11-29 06:45:20
rick schott

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!